Angel One SmartAPI Python: Login, Market Data and Orders
Published November 18, 2026 · Updated November 18, 2026 · In Indian Broker Automation Guides
Angel One SmartAPI Python code runs on smartapi-python, the official SDK that Angel One publishes on GitHub and PyPI (version 1.5.5 at the time of writing). With it, a script logs in with your client code, PIN and a TOTP, reads prices and candles, and places orders in your own account. Every method name and limit below comes from that SDK’s source and the SmartAPI documentation, checked on 18 November 2026.
This is a developer walkthrough. If you want finished software instead of a script, our Angel One API algo trading service builds it for you. The code here uses placeholders for every secret, and it places one small limit order that you confirm by hand.
On this page
- What you need before the first line of code
- Install the SDK and keep secrets out of the script
- Angel One SmartAPI Python login with PIN and TOTP
- Find the symbol token
- Read the LTP and candle data
- Place a limit order and confirm it
- Errors, rate limits and token expiry
- Static IP and the April 2026 algo rules
- When a tutorial script is not enough
- SmartAPI questions
What you need before the first line of code
SmartAPI is Angel One’s trading API, and it needs four things in place before any code runs:
- An Angel One trading account, plus a login on the SmartAPI portal.
- An app created there. The app gives you the API key that every request carries.
- A primary static IP registered on that app, with a secondary IP as an optional backup.
- TOTP switched on through the portal’s Enable TOTP page, and Python 3 on the machine with that IP.
The static IP matters most. Angel One’s order documentation says SmartAPI checks the source IP of every place, modify and cancel request against the registered address. A home connection with a changing address will fail on orders, even though logins and price reads still work.

Install the SDK and keep secrets out of the script
PyPI lists the package as smartapi-python, but you import it as SmartApi. Its PyPI entry only declares requests, six and python-dateutil. However, the module itself imports logzero and the websocket client, and the README asks for pyotp too. So install all of them together:
pip install smartapi-python pyotp logzero websocket-client
Every Angel One SmartAPI Python script needs four values, and they belong in environment variables. Your PIN and TOTP secret together can sign in to your account, so neither belongs in a .py file, a screenshot or a Git repository. In PowerShell, this sets them for the current window only:
$env:ANGEL_API_KEY = "your-api-key"
$env:ANGEL_CLIENT_CODE = "your-client-code"
$env:ANGEL_PIN = "your-pin"
$env:ANGEL_TOTP_SECRET = "your-totp-secret"
On Linux or macOS, use export with the same names. The TOTP secret is the text behind the QR code you scanned while enabling TOTP; the README calls it your QR value.
The SDK can leak secrets too. Its smartConnect.py logs a failed request together with its headers, which include your API key, and its parameters. For a failed login, those parameters hold your PIN and the TOTP. Therefore, keep the console output and any log files private.
Angel One SmartAPI Python login with PIN and TOTP
The SmartAPI User docs say a login needs a client code, a valid PIN and a TOTP. In the SDK, generateSession takes exactly those three. Its second argument has the name password, yet it carries your PIN. The script below is Python 3:
import os
import pyotp
from SmartApi import SmartConnect
from SmartApi.smartExceptions import SmartAPIException
CLIENT_CODE = os.environ["ANGEL_CLIENT_CODE"]
api = SmartConnect(api_key=os.environ["ANGEL_API_KEY"])
def ok(res):
# SmartAPI answers {"status": ..., "message": ..., "data": ...}
if not res or not res.get("status"):
raise RuntimeError(f"SmartAPI error: {res and res.get('message')}")
return res["data"]
def login():
totp = pyotp.TOTP(os.environ["ANGEL_TOTP_SECRET"]).now()
try:
res = api.generateSession(CLIENT_CODE, os.environ["ANGEL_PIN"], totp)
except SmartAPIException as e:
raise SystemExit(f"Login rejected: {e} (HTTP {e.code})")
return ok(res)["refreshToken"]
refresh_token = login()
print("Logged in")
A successful call stores the JWT and the feed token inside api, so later calls are signed for you. Login allows one request per second. The docs also say the session stays active until 12 midnight unless you log out. As a result, a bot that runs every trading day should log in again each morning with a fresh TOTP.

Find the symbol token
Orders and quotes need a symbol token, not just a name. Angel One publishes every tradable instrument in one JSON file, the OpenAPIScripMaster. For example, the copy we downloaded on 18 November 2026 had 169,806 rows, and its SBIN-EQ row on NSE shows token 3045 with a tick_size of 5.000000.
For a quick lookup inside a session, searchScrip works too:
for row in ok(api.searchScrip("NSE", "SBIN")):
print(row["tradingsymbol"], row["symboltoken"])
That endpoint allows one request per second. The Instruments docs say Angel One generates the dump once every day, so a bot can download the master file each morning and cache it.
Read the LTP and candle data
In the Angel One SmartAPI Python SDK, ltpData returns the last traded price, and getCandleData returns historical candles.
from datetime import datetime, timedelta
ltp = float(ok(api.ltpData("NSE", "SBIN-EQ", "3045"))["ltp"])
now = datetime.now()
candles = ok(api.getCandleData({
"exchange": "NSE",
"symboltoken": "3045",
"interval": "FIVE_MINUTE",
"fromdate": (now - timedelta(days=5)).strftime("%Y-%m-%d %H:%M"),
"todate": now.strftime("%Y-%m-%d %H:%M"),
}))
for ts, o, h, l, c, v in candles[-3:]:
print(ts, o, h, l, c, v)
According to the Historical docs, each record is a list of timestamp, open, high, low, close and volume, and dates use the format yyyy-MM-dd hh:mm. Each interval also has a cap on how many days fit in one request.

Candle requests allow 2 per second, 40 per minute and 2,000 per hour. Consequently, a backfill loop over many symbols needs a pause between calls.
Place a limit order and confirm it
The order below buys one SBIN share with a DAY limit order priced 1% under the last price. That price is unlikely to fill at once, which gives you time to see it in the app and cancel it. Because the tick size is 5 paise, the code rounds the price to 0.05.
tick = 0.05
price = round(ltp * 0.99 / tick) * tick
order = {
"variety": "NORMAL",
"tradingsymbol": "SBIN-EQ",
"symboltoken": "3045",
"transactiontype": "BUY",
"exchange": "NSE",
"ordertype": "LIMIT",
"producttype": "DELIVERY",
"duration": "DAY",
"price": f"{price:.2f}",
"quantity": "1",
}
placed = ok(api.placeOrderFullResponse(order))
print("orderid", placed["orderid"], "uniqueorderid", placed["uniqueorderid"])
details = api.individual_order_details(placed["uniqueorderid"])
print(details and details["data"]["orderstatus"])
Use placeOrderFullResponse rather than placeOrder. The shorter method logs a failure and returns None, so the reason never reaches your code. The full response keeps the message, and its uniqueorderid feeds the individual order status call.
Valid values come from the Order Constants table: variety NORMAL, STOPLOSS or ROBO, and product DELIVERY, CARRYFORWARD, MARGIN, INTRADAY or BO. Market and IOC values still appear there. Even so, Angel One’s April 2026 notice bars both for API algos.

Errors, rate limits and token expiry
The SDK fails in three different ways, and a long-running Angel One SmartAPI Python process has to catch all of them:
- It raises an exception. If the response carries an error type, the SDK raises a class from
smartExceptions, such as TokenException or OrderException. All of them inherit SmartAPIException and carry an HTTPcode. - It returns a false status. Other failures come back as a normal dictionary with status false and a message. The
ok()helper turns those into errors. - It lets a network error through. Timeouts come from requests itself. The SDK’s default timeout is 7 seconds.
Reads are safe to retry after a short pause. Orders are not. If a place call times out, the order may still have reached the exchange, so check the order book before you send it again.
import time
import requests
def read_with_retry(fn, *args, tries=3):
for attempt in range(tries):
try:
return ok(fn(*args))
except (SmartAPIException, requests.RequestException, RuntimeError) as e:
print(f"{fn.__name__} attempt {attempt + 1} failed: {e}")
time.sleep(1 + attempt)
raise RuntimeError(f"{fn.__name__} failed {tries} times")
api.setSessionExpiryHook(login) # runs on a 403 TokenException, before it is raised
ltp_data = read_with_retry(api.ltpData, "NSE", "SBIN-EQ", "3045")
Rate limits are counted per endpoint. The SmartAPI Rate Limit page says requests over the limit fail with 403 Access denied, and it counts place, modify and cancel together: 9 per second combined. The Exceptions page lists AG8001 for an invalid token and AG8002 for an expired one. When you finish, api.terminateSession(CLIENT_CODE) logs the session out.

Static IP and the April 2026 algo rules
Angel One’s notice on SmartAPI access from 1 April 2026 sets the rules your code runs under. Angel One accepts API orders only from your registered primary static IP, and you may change that IP no more than once a calendar week. The notice also says market and IOC orders are strictly prohibited for algorithmic trading.
NSE’s implementation standards (NSE/INVG/67858) set a threshold of 10 orders per second per exchange. Below it, an algo needs no individual registration and runs under a generic exchange algo ID. Above it, the algo needs its own exchange registration. Angel One’s notice repeats the same threshold.
The notice also wants retail algos hosted on the broker’s server. The exception is a client who writes their own logic and runs it from their own registered static IP, which is the setup the code above assumes. Running Angel One SmartAPI Python code for other people’s accounts is different, so read whether copy trading is legal in India first.
When a tutorial script is not enough
A script like this proves the connection. Production software also needs signal input, duplicate protection, a daily re-login, a static IP check, an order log and a way to stop it fast. For a bot that does those things, see our Angel One automation page. The Indian broker automation hub lists the other brokers we work with, including Upstox and Dhan. For linking SmartAPI to another platform, see broker API bridge development.
Stuck on an Angel One SmartAPI Python error, or want the whole bot built? Send us your rules and the error text on WhatsApp. You get a fixed quote, and we never ask for your PIN or TOTP secret.
SmartAPI questions
What is SmartAPI in Angel One?
SmartAPI is Angel One’s trading API. It covers login, orders, GTT rules, portfolio data, LTP, quotes, historical candles and a WebSocket feed. Angel One publishes official SDKs for it, including smartapi-python.
Is the Angel One SmartAPI Python SDK free?
Yes. The SDK is open source on GitHub, and the SmartAPI FAQ says the APIs are free of cost, even for historical data. Normal brokerage and charges on your trades still apply.
How do I get an API key from Angel One?
Sign in to the SmartAPI portal, create an app and register your primary static IP on it. The portal then shows the API key for that app. Treat it like a password.
What is the rate limit for Angel One SmartAPI?
It depends on the endpoint. Login allows 1 request per second, place, modify and cancel share 9 per second, LTP allows 10 per second, and candle data allows 2 per second. Requests over the limit return 403.
How long does a SmartAPI login stay valid?
Until 12 midnight, unless you log out first. Within the day, the SDK’s generateToken call swaps the refresh token for a new JWT, and SmartAPI allows it once per second and 1,000 times per hour.
Can a SmartAPI script place market orders?
Not for algo trading. Since 1 April 2026, Angel One’s notice prohibits market and IOC orders for algos, so send a LIMIT order with DAY duration instead.
Risk warning: Trading in equities and derivatives carries a risk of loss, and an automated script can place unwanted orders quickly if its logic or data is wrong. Test every change with the smallest possible quantity and watch the first orders by hand. The code above is an educational example, not tested production software, and it does not guarantee fills, prices or results. This article is not investment advice; check the current rules of SEBI, NSE and Angel One before you trade with an API.
Want this built for you?
We develop it as a service — reliable, tested, and yours to own.
Message Us on WhatsApp