Skip to main content

Angel One SmartAPI with Python: A Working Tutorial

FB THEFINBABA

Angel One's SmartAPI is free, including live market data — which makes it the usual starting point for anyone who does not want a monthly API bill while learning. The trade-off is that its login flow works quite differently from Zerodha's, and that difference is where most people get stuck on day one.

This Angel One SmartAPI Python walkthrough covers the whole path with runnable code: authentication, market data, placing an order, and streaming live ticks.

What you need first

  • An Angel One trading account.
  • An app created at smartapi.angelbroking.com — this gives you an API key.
  • Your client code, MPIN, and the TOTP secret you get while enabling two-factor authentication. Store the TOTP secret carefully; it is as sensitive as a password.
  • Python 3.8+ and two libraries.
pip install smartapi-python pyotp websocket-client

Keep all four credentials out of your code. Read them from environment variables or a config file your repository ignores.

Logging in: TOTP, not a browser redirect

This is the main difference from Kite Connect. Zerodha sends you to a browser, you log in, and it hands back a request token. SmartAPI instead expects your program to generate the current TOTP code itself and pass it in.

from SmartApi import SmartConnect
import pyotp

api_key     = 'your_api_key'
client_id   = 'your_client_code'
mpin        = 'your_mpin'
totp_secret = 'your_totp_secret'

obj  = SmartConnect(api_key=api_key)
totp = pyotp.TOTP(totp_secret).now()

data = obj.generateSession(client_id, mpin, totp)

auth_token    = data['data']['jwtToken']
refresh_token = data['data']['refreshToken']
feed_token    = obj.getfeedToken()

print('Logged in. Feed token:', feed_token)

Practically this means a SmartAPI bot can start itself in the morning without anyone opening a browser — genuinely convenient. It also means your TOTP secret sits on that machine, so treat the server's security as seriously as your account's.

Finding the symbol token

SmartAPI addresses instruments by a numeric symbol token, not by trading symbol. You look these up in the instrument master, which Angel One publishes as a JSON file.

import requests

URL = ('https://margincalculator.angelbroking.com/'
       'OpenAPI_File/files/OpenAPIScripMaster.json')

instruments = requests.get(URL).json()

sbin = next(i for i in instruments
            if i['symbol'] == 'SBIN-EQ' and i['exch_seg'] == 'NSE')

print(sbin['token'], sbin['symbol'])

That file is large. Download it once each morning and cache it — fetching it on every run is slow and unnecessary.

Placing an order

Orders are passed as a dictionary. Start with a single share while you are testing.

order = {
    'variety'         : 'NORMAL',
    'tradingsymbol'   : 'SBIN-EQ',
    'symboltoken'     : sbin['token'],
    'transactiontype' : 'BUY',
    'exchange'        : 'NSE',
    'ordertype'       : 'MARKET',
    'producttype'     : 'INTRADAY',
    'duration'        : 'DAY',
    'price'           : '0',
    'quantity'        : '1'
}

order_id = obj.placeOrder(order)
print('Order id:', order_id)

# Kya sach me bhara? Hamesha check karo
for o in obj.orderBook()['data']:
    if o['orderid'] == order_id:
        print(o['status'], o['averageprice'], o['text'])

As with any broker API, a successful call means the order reached Angel One — not that it was executed. Margin shortfalls, circuit limits and frozen quantities all produce rejections. Read the order book back every time.

Streaming live ticks

SmartAPI's WebSocket v2 needs the auth token, api key, client code and feed token from the login step.

from SmartApi.smartWebSocketV2 import SmartWebSocketV2

sws = SmartWebSocketV2(auth_token, api_key, client_id, feed_token)

token_list = [{'exchangeType': 1, 'tokens': [sbin['token']]}]  # 1 = NSE

def on_data(wsapp, message):
    print(message)

def on_open(wsapp):
    sws.subscribe('sub1', 1, token_list)   # mode 1 = LTP

sws.on_data  = on_data
sws.on_open  = on_open
sws.connect()

Keep the callback light. Push ticks onto a queue and do your strategy work elsewhere, or you will start dropping data during busy sessions.

Free API, but read this before you switch

SmartAPI costs nothing, including live and historical data, and for someone learning that removes a real barrier. Two things are worth weighing honestly.

First, reliability during live sessions is what you are actually paying for when you pay. Whether a free API holds up under pressure is something you should test with small size before trusting it with a full position.

Second, the flat-fee comparison depends entirely on your trading frequency. If you are placing a handful of orders a month, free wins comfortably. The full cost breakdown across brokers is in what Kite Connect actually costs.

The pragmatic approach that many traders settle on: learn and backtest on a free API, then decide which broker to run live money through once you know how often your strategy actually trades.

Frequently Asked Questions

Is Angel One SmartAPI free?

Yes. SmartAPI has no subscription charge and includes live market data and historical data, which is why it is a common starting point for people learning algo trading in India.

Why does SmartAPI need a TOTP secret?

SmartAPI does not use a browser redirect for login. Your program generates the current two-factor code itself using the TOTP secret and passes it to generateSession. It means the bot can log in unattended, but it also means the secret sits on that machine, so secure it accordingly.

What is a symbol token in SmartAPI?

A numeric identifier for an instrument. SmartAPI takes this token rather than the trading symbol, and you look it up in Angel One's instrument master JSON file. Download that file once a day and cache it rather than fetching it on every run.

Should I use Angel One or Zerodha for algo trading?

It depends on your trading frequency and how much you value execution reliability. Angel One's API is free, which suits learning and low-frequency strategies. A paid API like Kite Connect is easier to justify when live money is deployed daily and downtime is costly.

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