Skip to main content

Zerodha Kite Connect API with Python: A Working Tutorial

Almost every algo trading tutorial you find online is written for US markets. Alpaca, Interactive Brokers, the S&P 500. If you trade Indian markets, none of it maps cleanly onto how NSE actually works or how Zerodha's API is structured.

This Zerodha Kite Connect API Python tutorial covers the flow end to end with code you can run: authentication, market data, order placement and live tick streaming — plus the things that only break once real money is involved.

What you need before you start

Three things:

  • A Zerodha trading account.
  • A Kite Connect app created at developers.kite.trade. This is a paid developer subscription billed monthly by Zerodha, separate from your brokerage. You will get an api_key and an api_secret.
  • Python 3.8 or newer, and the official client library.
pip install kiteconnect

Keep your api_secret out of your code and out of version control. Read it from an environment variable or a config file that your repository ignores. This sounds obvious until the day a repo goes public with credentials in it.

Authentication: the part that confuses everyone

Kite Connect does not let you log in with a username and password from code. The flow is deliberately three-legged:

  1. You send the user to a login URL.
  2. After login, Zerodha redirects back with a request_token.
  3. You exchange that token, along with your secret, for an access_token.
from kiteconnect import KiteConnect

api_key = 'your_api_key'
api_secret = 'your_api_secret'

kite = KiteConnect(api_key=api_key)

# Step 1 - open this URL in a browser and log in
print(kite.login_url())

# Step 2 - after redirect, copy request_token from the URL
request_token = 'paste_request_token_here'

# Step 3 - exchange it for an access token
data = kite.generate_session(request_token, api_secret=api_secret)
kite.set_access_token(data['access_token'])

print('Access token:', data['access_token'])

The important detail: that access token expires every morning. It is not a permanent key. Any bot you write has to account for a fresh token each trading day.

Fetching market data

Once authenticated, quotes are straightforward. Instruments are addressed as EXCHANGE:TRADINGSYMBOL.

# Last traded price
print(kite.ltp('NSE:INFY'))

# Full quote - depth, OHLC, volume
print(kite.quote('NSE:INFY'))

# Your holdings and positions
print(kite.holdings())
print(kite.positions())

For historical data you need the numeric instrument_token rather than the symbol. Download the instrument dump once per day and look it up:

import datetime

instruments = kite.instruments('NSE')
token = next(i['instrument_token'] for i in instruments
             if i['tradingsymbol'] == 'INFY')

candles = kite.historical_data(
    instrument_token=token,
    from_date=datetime.date(2026, 1, 1),
    to_date=datetime.date(2026, 3, 31),
    interval='day'
)

for c in candles[:5]:
    print(c['date'], c['open'], c['high'], c['low'], c['close'])

Do not call instruments() on every run — it returns a large payload. Cache it to disk each morning.

Placing your first order

Place your first orders with one share, and place them when you can watch what happens.

order_id = kite.place_order(
    variety=kite.VARIETY_REGULAR,
    exchange=kite.EXCHANGE_NSE,
    tradingsymbol='INFY',
    transaction_type=kite.TRANSACTION_TYPE_BUY,
    quantity=1,
    product=kite.PRODUCT_CNC,
    order_type=kite.ORDER_TYPE_MARKET
)

print('Order placed:', order_id)

# Always check what actually happened
for o in kite.orders():
    if o['order_id'] == order_id:
        print(o['status'], o['average_price'], o['status_message'])

A successful API call means the order reached Zerodha, not that it was filled. Orders get rejected for margin shortfalls, circuit limits, frozen quantities and closed markets. Read the status back every time — assuming success is how bots end up with positions their owner does not know about.

Streaming live ticks with WebSocket

Polling quotes in a loop will hit rate limits fast. For live data, use the WebSocket client:

from kiteconnect import KiteTicker

kws = KiteTicker(api_key, data['access_token'])

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

def on_connect(ws, response):
    ws.subscribe([token])
    ws.set_mode(ws.MODE_FULL, [token])

def on_close(ws, code, reason):
    print('closed:', code, reason)

kws.on_ticks = on_ticks
kws.on_connect = on_connect
kws.on_close = on_close

kws.connect()

The ticker runs its own event loop, so keep your strategy logic light inside on_ticks. Push work onto a queue and process it elsewhere — blocking the callback means dropped ticks.

What breaks once it is running for real

The code above works. Keeping it running for months is a different problem:

  • The daily token. Your bot needs a fresh access token every trading morning before the market opens.
  • Reconnection. WebSockets drop. Handle reconnects and resubscribe, or you will silently stop receiving data mid-session.
  • Your laptop is not a server. Sleep, Wi-Fi drops and Windows updates all end a trading session. A small cloud VPS solves this properly.
  • Static IP. Under SEBI's algo trading framework, retail traders using broker APIs are expected to register a static IP with the broker. A VPS gives you one.
  • Rate limits. Kite enforces per-second and per-endpoint limits. Build backoff in from the start rather than after you get throttled.
  • The subscription. Live data and historical candles need the paid Connect plan — see what Kite Connect actually costs before you build around them.

None of this is difficult, but all of it is the difference between a script that works on a Sunday afternoon and a system that trades on Monday morning.

Frequently Asked Questions

Is Kite Connect free to use?

No. Kite Connect is a paid developer subscription from Zerodha, billed monthly and separate from your normal brokerage charges. You create the app and see current pricing at developers.kite.trade.

Why does my Zerodha access token stop working every day?

That is by design. The Kite Connect access token is valid for a single trading day and expires the next morning, so your program has to complete the login exchange again each day before the market opens. It is not a bug in your code.

Do I need to know advanced Python for algo trading?

No. Variables, lists, dictionaries, functions and loops cover most of what a trading bot needs. The harder part is market mechanics and risk management, not the language itself.

Can I run my trading bot on my laptop?

You can while learning, but not reliably in production. Sleep mode, Wi-Fi drops and OS updates will interrupt a live session. A small cloud VPS with a static IP is the standard setup, and it also satisfies the static IP registration expected under SEBI's algo framework.

Disclaimer: TheFinBaba provides educational content only - this is not investment advice. Trading involves risk of loss.

Atul Shrivastava
Written by

Atul Shrivastava

Founder & Lead Trainer, TheFinBaba

16+ years in the markets. 8+ years teaching Python algo trading.

Full profile

Found this useful? Share it:

WhatsApp Share

Disclaimer: TheFinBaba provides educational content only. Nothing in this article is investment advice or a recommendation to buy or sell any security. Trading in financial markets carries risk of loss — make every decision based on your own research and risk capacity.

Free Account Opening

Open a Free Demat & Trading Account in 5 Minutes

Start trading stocks, F&O, IPOs, bonds & ETFs with Zerodha — India's most trusted discount broker. Zero account-opening fee, paperless Aadhaar KYC, and the best APIs (Kite Connect) for Python algo trading.

  • Zero account-opening fee
  • ₹0 brokerage on equity delivery
  • Kite Connect API — best for Python algo traders
  • Paperless Aadhaar e-KYC in 5 minutes
Open Free Demat Account

* Zerodha is SEBI-registered. Account opening subject to KYC approval. Atul Shrivastava is an Authorised Person (AP) — Reg AP2516003481.

Trusted by 1.6 Cr+ Indian Investors

Zerodha is India's largest stock broker by active clients (NSE data, 2026).

₹0
Delivery
₹20
Intraday
5 min
Opening