Register
Learn guide

Build Your First Python Trading Bot in India

Zerodha's Kite Connect API lets your own Python code place orders, read your account and stream live prices. This guide to Python for algo trading covers the plans, the rules that apply since April 2026, the daily login, and working code for instruments, orders, stop losses, live prices and historical data.

QuantPower Research · Updated 16 Nov 2026 · 17 min read

To place orders through Kite Connect you need a static IP registered with Zerodha, a fresh login each trading day, and a market protection setting on market orders; live and historical market data need Zerodha's plan that includes data.12 The sections below explain why Python became the common language for this work, how to structure a small trading script, a complete example strategy, how to test it on past data, how to run it every day, the errors you will meet, and when a no-code platform is the simpler route. The code is for learning: test it with small quantities and check Zerodha's current documentation, because parameters and rules change.

What you need

  • A Zerodha account, with F&O enabled if you trade derivatives.
  • A Kite Connect developer account, from Zerodha's developer site.
  • Python 3 and Zerodha's official kiteconnect library.
  • A static IP address registered with Zerodha. Most home broadband connections do not have one, so many traders run their code on a cloud server with a fixed IP.
  • Zerodha's plan with market data, if you need live prices or historical candles.

A short history of Python in trading

For decades, automated trading belonged to firms with their own developers, data feeds and exchange connections. Retail traders who wanted to test rules used spreadsheets or desktop charting software with its own scripting language. Python changed who could do the work. The language itself dates from 1991, but its use in finance took off after the NumPy library for fast numerical arrays (2006) and the pandas library for time series and tables, which Wes McKinney began at the investment firm AQR in 2008 and released as open source in 2009.3 With those two libraries, a trader could load years of prices, calculate indicators and test a rule in a few lines.

In India, the missing piece was a broker that let individuals connect their own code. Zerodha's Kite Connect, and later similar APIs at other brokers, opened order placement and market data to anyone with a developer account. Through the late 2010s a large community of Indian retail coders grew around these APIs, sharing scripts for straddles, breakouts and option chain analysis.

The rules then caught up. SEBI's circular of 4 February 2025 on safer participation of retail investors in algorithmic trading set conditions for API trading: no open APIs, a unique API key per client, two-factor login, and orders only from static IP addresses registered with the broker, with algos above 10 orders a second registered with the exchange.4 The framework applied to every broker from 1 April 2026, and Zerodha made a registered static IP mandatory for order placement through Kite Connect from that date.1

Why traders use Python

  • Libraries. pandas for prices and results, NumPy for calculations, and many open-source packages for indicators, statistics and plotting.
  • The broker library. Zerodha maintains an official Python client for Kite Connect, so login, orders and data take a few calls each.
  • One language for research and trading. The same code can test a rule on history and run it live, which reduces the gap between the backtest and the market.
  • Readable code. A strategy written in plain Python is easy to review, which matters when the code spends your money.

Python also has limits. It is slower than compiled languages, which does not matter for strategies that trade a few times a day, and it puts every operational task on you: servers, logins, retries and records.

Kite Connect plans

Zerodha offers a plan without market data, which covers orders, GTT, margins, holdings and positions, and a plan with market data, which adds live prices over WebSocket and historical candles. Strategies that react to prices need the plan with data. Plans, fees and any waivers for active users change, so check the current terms on Zerodha's Kite Connect pages before you subscribe.5

Rules your code must follow

These come from SEBI's retail algo framework and the exchange rules in force since 1 April 2026, as Zerodha applies them.

  • Static IP: orders, modifications and cancellations must come from a static IP registered in your developer account, whatever your order rate. Other calls, such as positions or market data, work from any IP.1 You can register a primary and a secondary IP, and the list can change once a calendar week.2 Zerodha's terms allow a static IP to be shared only within your immediate family.
  • Order rate: Zerodha's API accepts up to 10 order requests a second per trading account. Requests above that fail with HTTP error 429.
  • Market protection: market and SL-M orders sent through the API carry market protection, which keeps the fill within a range of the last price. The library takes it as a percentage, or -1 for automatic.2
  • Daily login: the access token expires every day, so you log in again each trading day.
  • Registration: your own code sending fewer than 10 orders a second, used for your account or your immediate family's, does not need exchange registration. See the guide to SEBI rules for option trading.

Install the library and log in

Terminal
pip install --upgrade kiteconnect

Create an app in the developer console with a redirect URL. You receive an API key and an API secret. Logging in then takes four steps:

  1. Your code prints a login URL.
  2. You open it, log in with your Zerodha password and two-factor code, and approve the app.
  3. Zerodha sends you to your redirect URL with a request_token in the address.
  4. Your code exchanges the request token and your API secret for an access token.
Flow of the Kite Connect daily login, from the login URL to the access token and orders from a registered static IP (illustration)
Python
import os
from kiteconnect import KiteConnect

kite = KiteConnect(api_key=os.environ["KITE_API_KEY"])
print(kite.login_url())  # open this link and log in

request_token = input("request_token from the redirect URL: ")
session = kite.generate_session(request_token, api_secret=os.environ["KITE_API_SECRET"])
kite.set_access_token(session["access_token"])

print("Logged in as", kite.profile()["user_name"])

Keep the API key, secret and access token in environment variables or a secrets manager, never in code you share. The login needs your own hands on the two-factor step each morning; scripts that try to automate the password and two-factor code break Zerodha's terms and put your account at risk.

Find the instrument

Option symbols change with every expiry, so look them up instead of typing them. The instruments list gives each contract's trading symbol, expiry, strike and lot size.

Python
import datetime as dt

nfo = kite.instruments("NFO")
calls = [i for i in nfo if i["name"] == "NIFTY" and i["instrument_type"] == "CE"
         and i["expiry"] >= dt.date.today()]
expiry = min(i["expiry"] for i in calls)
atm = next(i for i in calls if i["expiry"] == expiry and i["strike"] == 25000)

print(atm["tradingsymbol"], atm["lot_size"])

The list is large and changes daily, so download it once each morning and keep it in memory. Take the lot size from it rather than typing it: Nifty's lot became 65 and Bank Nifty's 30 from the January 2026 series.6

Read prices

Quotes need the plan with market data.

Python
key = "NFO:" + atm["tradingsymbol"]
quote = kite.ltp(["NSE:NIFTY 50", key])
nifty = quote["NSE:NIFTY 50"]["last_price"]
option = quote[key]["last_price"]

Place an order

A limit order fills at your price or better, which makes it the simplest choice for options.

Python
order_id = kite.place_order(
    variety=kite.VARIETY_REGULAR,
    exchange=kite.EXCHANGE_NFO,
    tradingsymbol=atm["tradingsymbol"],
    transaction_type=kite.TRANSACTION_TYPE_BUY,
    quantity=atm["lot_size"],
    product=kite.PRODUCT_NRML,
    order_type=kite.ORDER_TYPE_LIMIT,
    price=round(option + 0.5, 1),
    tag="nifty_atm_buy",
)

For a market order, add market_protection=-1 for automatic protection, or a percentage such as 2. Older versions of the library do not accept this parameter, so keep it up to date.

Every order passes Zerodha's risk checks before it reaches the exchange. Check its status before you act on it:

Python
status = kite.order_history(order_id)[-1]["status"]  # OPEN, COMPLETE, REJECTED...

Add a stop loss

Once the buy order shows COMPLETE, place a stop-loss limit order. NSE does not accept SL-M orders in index options, so use an SL order with a gap between the trigger and the limit.7

Python
kite.place_order(
    variety=kite.VARIETY_REGULAR,
    exchange=kite.EXCHANGE_NFO,
    tradingsymbol=atm["tradingsymbol"],
    transaction_type=kite.TRANSACTION_TYPE_SELL,
    quantity=atm["lot_size"],
    product=kite.PRODUCT_NRML,
    order_type=kite.ORDER_TYPE_SL,
    trigger_price=240,
    price=235,
)

The gap between trigger and limit is a trade-off: too small and a fast fall jumps past the limit, leaving the stop unfilled; too large and the fill can be far below the trigger.

Stream live prices

The WebSocket feed sends price updates as they happen, for strategies that react during the day. It needs the plan with market data.

Python
from kiteconnect import KiteTicker

ticker = KiteTicker(os.environ["KITE_API_KEY"], session["access_token"])

def on_connect(ws, response):
    ws.subscribe([256265])  # Nifty 50 index
    ws.set_mode(ws.MODE_LTP, [256265])

def on_ticks(ws, ticks):
    for t in ticks:
        print(t["instrument_token"], t["last_price"])

ticker.on_connect = on_connect
ticker.on_ticks = on_ticks
ticker.connect()

Get historical data

Historical candles let you test rules on past data before trading them. They need the plan with market data.

Python
candles = kite.historical_data(
    256265, dt.datetime(2026, 9, 1), dt.datetime(2026, 9, 30, 15, 30), "15minute"
)
print(candles[0])  # date, open, high, low, close, volume

How to structure a small trading script

Most problems in live scripts come from structure, not from the strategy. A simple layout keeps each concern in one place:

PartWhat it does
SettingsSymbols, quantities, times, limits, read from a file, not hard-coded
SessionThe morning login, the access token, a check that the token works
DataInstruments, quotes, candles, with retries and timeouts
SignalThe rule itself: a function that takes prices and returns buy, sell or nothing
OrdersOne function that places every order, records it and checks its status
RiskChecks before every order: maximum quantity, orders a day, daily loss
LogOne line per decision and per order, written to a file
ExitThe emergency exit that cancels orders and closes positions

Keeping all order placement in one function matters most. It is the only place to add a check, and it means a bug elsewhere cannot send an order by accident.

A complete example: a 9:20 short straddle

The sketch below sells the at-the-money Nifty call and put at 9:20 am with a stop on each leg and exits at 3:10 pm. It shows the structure, not a strategy to trade; on its own it has no handling for partial fills, rejections or lost connections.

Python
import datetime as dt, time

def atm_strike(spot, step=50):
    return int(round(spot / step) * step)

def leg(nfo, kind, strike, expiry):
    return next(i for i in nfo if i["name"] == "NIFTY" and i["instrument_type"] == kind
                and i["strike"] == strike and i["expiry"] == expiry)

def sell_with_stop(inst, stop_pct=0.30):
    key = "NFO:" + inst["tradingsymbol"]
    price = kite.ltp([key])[key]["last_price"]
    kite.place_order(variety=kite.VARIETY_REGULAR, exchange=kite.EXCHANGE_NFO,
                     tradingsymbol=inst["tradingsymbol"], transaction_type=kite.TRANSACTION_TYPE_SELL,
                     quantity=inst["lot_size"], product=kite.PRODUCT_MIS,
                     order_type=kite.ORDER_TYPE_LIMIT, price=round(price - 0.5, 1))
    trigger = round(price * (1 + stop_pct), 1)
    kite.place_order(variety=kite.VARIETY_REGULAR, exchange=kite.EXCHANGE_NFO,
                     tradingsymbol=inst["tradingsymbol"], transaction_type=kite.TRANSACTION_TYPE_BUY,
                     quantity=inst["lot_size"], product=kite.PRODUCT_MIS,
                     order_type=kite.ORDER_TYPE_SL, trigger_price=trigger, price=round(trigger + 5, 1))

while dt.datetime.now().time() < dt.time(9, 20):
    time.sleep(1)

spot = kite.ltp(["NSE:NIFTY 50"])["NSE:NIFTY 50"]["last_price"]
nfo = kite.instruments("NFO")
expiry = min(i["expiry"] for i in nfo if i["name"] == "NIFTY" and i["expiry"] >= dt.date.today())
strike = atm_strike(spot)
for kind in ("CE", "PE"):
    sell_with_stop(leg(nfo, kind, strike, expiry))

while dt.datetime.now().time() < dt.time(15, 10):
    time.sleep(5)
exit_all()  # defined in the emergency exit section below

Even this short script needs to wait for the sells to fill before placing stops, to handle a stop that fills while the other leg is still open, and to log every step. Each of those is a few more lines and a few more ways to fail.

Testing a rule on past data

Before any rule trades, test it on history with pandas:

Python
import pandas as pd

df = pd.DataFrame(candles).set_index("date")
df["ema20"] = df["close"].ewm(span=20, adjust=False).mean()
df["ema50"] = df["close"].ewm(span=50, adjust=False).mean()
df["signal"] = (df["ema20"] > df["ema50"]).astype(int)
df["position"] = df["signal"].shift(1).fillna(0)   # act on the next candle, not this one
df["ret"] = df["close"].pct_change() * df["position"]
print(df["ret"].sum())

The shift(1) line is the most important one in any test: it makes the rule act on the candle after the signal, which is when a real order could be placed. Without it, the test uses the close of a candle before it has happened, a classic look-ahead error. Add costs and slippage to every trade, test on more than one period, and treat a result that depends on one setting with suspicion.

Python tools worth knowing

A trading script needs only a few libraries beyond the broker client:

LibraryUse
pandasCandles, signals and trade lists as tables; resampling 1-minute data to 5 or 15 minutes
NumPyFast calculations on arrays of prices
The standard logging moduleTimestamped logs of every decision and order
The standard datetime and zoneinfo modulesMarket times in Indian Standard Time, whatever the server's own time zone
A schedulerStarting the script before the open and stopping it after the close

Indicator calculations such as moving averages, RSI and ATR take a few lines of pandas each. Writing them yourself, and checking them against a chart, is a good way to make sure the backtest and the live script calculate exactly the same thing.

Python and other broker APIs

The structure in this guide carries over to other Indian brokers' APIs. Each has its own client library, login flow and parameter names, but the same rules apply to all of them since 1 April 2026: a unique API key, a two-factor login each day, orders only from a registered static IP, and exchange registration above 10 orders a second.4 If you write your strategy logic separately from the broker calls, as in the structure table above, moving to another broker means rewriting only the session, data and order parts. Keep a thin layer of your own functions, such as place, cancel and positions, between the strategy and the broker's library, so the strategy never calls the library directly.

Expiry days and lot sizes in code

Two things change more often than coders expect, and both should come from data, not from constants in the code:

  • Expiry days. NSE equity derivatives have expired on Tuesdays since 1 September 2025, and when that day is a holiday they expire on the previous trading day. Scripts written for Thursday expiries broke that week. Take the expiry from the instruments list, as in the examples above.
  • Lot sizes. Index lot sizes were revised for the January 2026 series.6 Take lot_size from the instruments list each morning.

The same applies to tick sizes, freeze quantities and the list of weekly-expiry indices: read them, do not assume them.

Using GTT orders from Python

For positions held overnight, a GTT order sits at Zerodha and fires when the price reaches a trigger, even when your script is not running. A two-leg GTT can hold both a stop and a target, and whichever fires first cancels the other.

Python
kite.place_gtt(
    trigger_type=kite.GTT_TYPE_OCO,
    tradingsymbol="INFY", exchange="NSE",
    trigger_values=[1450, 1620], last_price=1530,
    orders=[
        {"transaction_type": kite.TRANSACTION_TYPE_SELL, "quantity": 20,
         "order_type": kite.ORDER_TYPE_LIMIT, "product": kite.PRODUCT_CNC, "price": 1445},
        {"transaction_type": kite.TRANSACTION_TYPE_SELL, "quantity": 20,
         "order_type": kite.ORDER_TYPE_LIMIT, "product": kite.PRODUCT_CNC, "price": 1620},
    ],
)

A GTT is useful precisely because it does not depend on your script staying alive. Use it for swing positions; for intraday strategies, a stop-loss order at the exchange does the same job for the day.

Handling orders safely

Most money lost to trading scripts is lost through order handling, not through bad strategies. A few habits prevent the worst cases:

  • Never retry blindly. If a call to place an order times out, the order may still have reached Zerodha. Check the order book for your tag before sending it again; a blind retry can double the position.
  • Tag every order. The tag field lets you find your script's orders in the order book and tell them apart from manual ones.
  • Wait for the fill. Do not place a stop for a position that has not been filled, and do not assume a limit order filled because it was accepted.
  • Expect partial fills. A limit order for several lots can fill one lot and wait for the rest. Place stops for the quantity actually filled.
  • Cap everything. A maximum quantity per order, a maximum number of orders per day and a daily loss limit checked before every order stop a bug from becoming a disaster.
  • Close on failure. If an entry with several legs half fails, decide in advance whether to close the filled legs or complete the rest, and write that into the code.

Handling a lost connection

Live scripts lose their connection more often than you expect: a server restart, a network hiccup, a token that expires.

  • The WebSocket can drop. The KiteTicker client can reconnect on its own; make sure your on_connect handler subscribes again to every instrument after a reconnect.
  • Missed prices during a gap mean your stop logic did not run. After a reconnect, check positions and orders before doing anything else.
  • A crashed script leaves orders at the exchange. Broker-side stop-loss orders protect positions even when your script is down; logic that lives only in the script does not.
  • A health check that messages you when no price has arrived for a minute during market hours turns a silent failure into a visible one.

Costs to count in your code

Costs belong in both the backtest and the live script. Since 1 April 2026, STT is 0.15% of the premium on every option sale and 0.05% of the value on every futures sale.8 On top come brokerage per order at your broker's rate, exchange transaction charges, SEBI fees, stamp duty on purchases and GST on brokerage and exchange charges.

A short straddle that sells two Nifty options and buys them back each day places four orders. At ₹20 an order that is ₹80 a day in brokerage alone, plus STT on the two sales, every trading day. A rule that makes a few points a day before costs can lose money after them. Put a cost function in the code and subtract it from every simulated and every real trade.

Keeping keys and the server secure

  • Keys out of code. API key, secret and access token in environment variables or a secrets manager; never in a repository, never in a chat.
  • A locked-down server. SSH keys instead of passwords, only the ports you need open, automatic security updates on.
  • One purpose. The trading server runs the trading script and nothing else.
  • Limited access. Only you can log in, and the server's static IP is registered only to your Zerodha account.

A leaked API secret with a valid access token lets someone else place orders on your account until the token expires. Treat both like your trading password.

A testing ladder

Move a strategy from idea to live money in steps:

  1. Backtest on at least a year of candles, with costs, slippage and the next-candle rule.
  2. Paper run on live prices without orders: let the script log what it would have done for a few weeks.
  3. One lot live, with all limits set low, for a few more weeks.
  4. Compare the live trades with the paper log and the backtest for the same days.
  5. Scale up slowly, only if the three agree.

Skipping the paper run is the commonest shortcut and the most expensive one: it is where order-handling bugs show up for free.

Running the script every day

  • A server with the registered IP. A small cloud server with a fixed public address, registered as your static IP.
  • A schedule. Start the script before the open, after your manual login, and stop it after the close.
  • Monitoring. A message to your phone when an order is rejected, when the script stops, or when the daily loss limit is reached.
  • Records. Keep each day's log and contract notes; they are your record for tax and for reviewing the strategy.
  • Updates. Keep the library current, because Zerodha changes parameters such as market protection.

An emergency exit

Every script needs a way to stop everything at once. This function cancels open orders and closes open positions.

Python
def exit_all():
    for o in kite.orders():
        if o["status"] in ("OPEN", "TRIGGER PENDING"):
            kite.cancel_order(o["variety"], o["order_id"])
    for p in kite.positions()["net"]:
        if p["quantity"]:
            kite.place_order(
                variety=kite.VARIETY_REGULAR,
                exchange=p["exchange"],
                tradingsymbol=p["tradingsymbol"],
                transaction_type=kite.TRANSACTION_TYPE_SELL if p["quantity"] > 0 else kite.TRANSACTION_TYPE_BUY,
                quantity=abs(p["quantity"]),
                product=p["product"],
                order_type=kite.ORDER_TYPE_MARKET,
                market_protection=-1,
            )

Positions larger than the exchange's freeze quantity have to be closed in several orders.

What a live script also needs

  • A morning routine that logs in, downloads instruments and checks funds with kite.margins().
  • Risk checks before every order: maximum quantity, maximum orders per day and a daily loss limit.
  • A log of every order request and response.
  • Handling for rejections, partial fills and lost connections.
  • A server with your registered static IP, running through market hours.

Common errors

ErrorLikely causeFix
TokenExceptionThe access token has expiredLog in again and create a new session
Market orders without market protection are not allowed via APIA market or SL-M order was sent without market protectionAdd market_protection or use a limit order
Order rejected for IPThe request came from an IP not registered with ZerodhaRegister your server's public IP, and check it is the address your code actually sends from
HTTP 429More than 10 orders per secondSpace out requests, and split large orders into no more than 10 slices
Quote or historical calls failThe plan has no market dataUse the plan with market data
Quantity rejectedNot a multiple of the lot sizeTake lot_size from the instruments list

Common mistakes in trading scripts

  • Server time instead of market time. A cloud server in another time zone starts the script at the wrong hour. Always work in Indian Standard Time.
  • Floating-point prices. Prices must be rounded to the contract's tick size, or the order is rejected.
  • Hard-coded symbols. Option symbols change every expiry; look them up each day.
  • Trusting the backtest's fills. Live fills are worse than candle prices, especially for market orders at the open and the close.
  • No position check at start. A script restarted mid-day can open a second set of positions if it does not first read what is already open.
  • Silent exceptions. A try block that hides errors keeps the script running while it does nothing useful. Log every exception and alert yourself.
  • Testing on live money first. Every one of these mistakes is cheap to find in a paper run and expensive to find in a live one.

Writing code or using a platform

Your own code gives you full control, and Python is a good language for it. It also makes you responsible for the server, the static IP, the daily login, error handling and testing.

QuantPower runs strategies on your Zerodha account without code. It is trading software, not a broker, and it handles the parts a script leaves to you:

In your scriptIn QuantPower
A cloud server with a fixed IPTwo static IPs included with your account, to register with Zerodha
The morning login codeA Sign in button that opens Zerodha's own page
Strike-finding codeA rule leg such as "ATM" or "OTM 2", or a strike picked by delta
Stop and target loopsStops, targets, trailing stops and M2M exits on each leg and each algo
Your own risk checksA kill switch, a daily loss limit and Smart Exit across the account
Your log filesAn activity log on every algo

You build rules in the strategy builder, test them with backtesting and forward test, and switch them on live. Your funds and securities stay with Zerodha, and orders go to Zerodha through its official API from your static IPs. See Zerodha algo trading for the setup. Many traders keep Python for research and run the strategies they trade every day as algos.

Where Python trading in India is going

The 2026 rules have made the operational side of personal algo trading heavier: a registered IP, a daily login, market protection, order-rate limits. At the same time, AI coding assistants have made the code itself easier to write. The result is that writing a strategy is quicker than ever, while running it safely every day is the harder part. Traders who code tend to put more care into testing, logging and risk checks, and to hand the routine running of proven rules to software built for it. Python will stay the language of research for Indian retail traders, because the libraries and the community are already there; what changes is how much of the daily running is done by hand.

Frequently asked questions

Does Kite Connect include market data?

Only on Zerodha's plan with market data. The plan without data covers orders and account data. Check Zerodha's current pricing before you subscribe.

Do I need a static IP for Kite Connect?

Yes, to place, modify or cancel orders, whatever your order rate. Other calls work from any IP.

Does my Python algo need SEBI registration?

Not if it sends fewer than 10 orders a second and trades only your account or your immediate family's. Faster algos must be registered with the exchange through your broker.

Can I run my script on my laptop?

Only if your internet connection has a static IP registered with Zerodha. Most home connections do not, so traders use a cloud server.

Why are my market orders rejected?

Market and SL-M orders through the API need a market protection value. Add market_protection to the order, or use a limit order.

How do I avoid look-ahead bias in a pandas backtest?

Act on the candle after the signal, for example with shift(1) on the position column, and never use a candle's close before it has closed.

Start with 500 free tokens

Connect your broker, build a strategy and test it on paper before a single live order goes out.

References

  1. Zerodha support: static IP for Kite Connect, mandatory for API order placement from 1 April 2026 (support.zerodha.com)
  2. Kite Connect forum: market protection and static IP, March 2026, and "Preparing to comply with SEBI's retail algo rules" (kite.trade)
  3. Wes McKinney, *Python for Data Analysis* (O'Reilly), on the origins of pandas at AQR in 2008
  4. SEBI, circular on safer participation of retail investors in algorithmic trading, 4 February 2025, and glide-path circular, 30 September 2025 (sebi.gov.in)
  5. Zerodha, Kite Connect API documentation (kite.trade) and "What are the charges for Kite APIs?" (support.zerodha.com)
  6. NSE, revision of market lot sizes of index derivatives from the January 2026 series (nseindia.com)
  7. NSE, circular NSE/FAOP/49677 on the discontinuation of stop-loss market orders in options, September 2021 (nseindia.com)
  8. Union Budget 2026-27: STT on the sale of futures raised from 0.02% to 0.05%, and on the sale of options from 0.10% to 0.15% of the premium, from 1 April 2026 (incometaxindia.gov.in)
Trading involves substantial risk. The code here is for learning. Test it with small quantities before relying on it, and check Zerodha's current API documentation, as parameters and rules change.