As per NSE guidelines for retail algorithmic trading, SmartAPI access now requires a registered Static IP. 🗓 Effective: 01-Apr-2026
SmartAPI - Python is a library for interacting with Angel Broking's trading platform. It provides REST-like HTTP APIs for building stock market investment and trading applications, including real-time order execution.
Use pip to install the latest release:
pip install smartapi-pythonIf you want to work with the latest code:
git clone https://github.com/angel-one/smartapi-python.git
cd smartapi-pythonpip install -r requirements_dev.txtTo install development dependencies directly without cloning the repo:
pip install -r https://raw.githubusercontent.com/angel-one/smartapi-python/main/requirements_dev.txt
For cryptographic support, install pycryptodome (make sure to uninstall pycrypto first if it's installed):
pip uninstall pycrypto
pip install pycryptodomeimportpyotpfromSmartApiimportSmartConnectfromSmartApi.loggerConfigimportget_loggerlogger=get_logger(__name__, "INFO")
client_info= {
"api_key": "Your Api Key",
"client_id": "Your client code",
"password": "Your pin",
"totp_secret": "Your QR value",
}
try:
# Generate TOTP token from secrettotp=pyotp.TOTP(client_info["totp_secret"]).now()
exceptExceptionase:
logger.error("Invalid Token: The provided token is not valid.")
raiseesmartApi=SmartConnect(api_key=client_info["api_key"])
response=smartApi.generateSession(client_info["client_id"], client_info["password"], totp)
ifresponse.get('status'):
logger.info("Login successful!")
else:
logger.error("Login failed!")
logger.error(response)profile=smartApi.getProfile(refreshToken=smartApi.getrefreshToken)
logger.info(profile)try:
orderparams= {
"variety": "NORMAL",
"tradingsymbol": "SBIN-EQ",
"symboltoken": "3045",
"transactiontype": "BUY",
"exchange": "NSE",
"ordertype": "LIMIT",
"producttype": "INTRADAY",
"duration": "DAY",
"price": "19500",
"squareoff": "0",
"stoploss": "0",
"quantity": "1"
}
orderid=smartApi.placeOrder(orderparams)
logger.info(f"Order placed successfully. Order ID: {orderid}")
exceptExceptionase:
logger.exception(f"Order placement failed: {e}")# Create GTT Ruletry:
gttCreateParams= {
"tradingsymbol": "SBIN-EQ",
"symboltoken": "3045",
"exchange": "NSE", "producttype": "MARGIN",
"transactiontype": "BUY",
"price": 100000,
"qty": 10,
"disclosedqty": 10,
"triggerprice": 200000,
"timeperiod": 365
}
rule_id=smartApi.gttCreateRule(gttCreateParams)
logger.info(f"GTT rule created. Rule ID: {rule_id}")
exceptExceptionase:
logger.exception(f"GTT Rule creation failed: {e}")
# Fetch GTT Rule Listtry:
status= ["FORALL"]
page=1count=10gtt_list=smartApi.gttLists(status, page, count)
logger.info(f"GTT Rules: {gtt_list}")
exceptExceptionase:
logger.exception(f"GTT Rule List fetch failed: {e}")try:
historicParam= {
"exchange": "NSE",
"symboltoken": "3045",
"interval": "ONE_MINUTE",
"fromdate": "2025-08-08 09:15", "todate": "2025-09-08 15:15"
}
candle_data=smartApi.getCandleData(historicParam)
logger.info(candle_data)
exceptExceptionase:
logger.exception(f"Historic API failed: {e}")try:
logout=smartApi.terminateSession(client_info["client_id"])
logger.info("Logout Successful")
exceptExceptionase:
logger.exception(f"Logout failed: {e}")fromSmartApi.smartWebSocketV2importSmartWebSocketV2fromSmartApi.loggerConfigimportget_loggerlogger=get_logger(__name__, "INFO")
AUTH_TOKEN=smartApi.getaccessTokenAPI_KEY=client_info["api_key"]
CLIENT_CODE=client_info["client_id"]
FEED_TOKEN=smartApi.getfeedTokencorrelation_id="abc123"action=1mode=1token_list= [
{
"exchangeType": 1,
"tokens": ["99926009", "99926000"]
}
]
sws=SmartWebSocketV2(AUTH_TOKEN, API_KEY, CLIENT_CODE, FEED_TOKEN)
defon_data(wsapp, message):
logger.info(f"Ticks: {message}")
defon_open(wsapp):
logger.info("WebSocket opened")
sws.subscribe(correlation_id, mode, token_list)
defon_error(wsapp, error):
logger.error(error)
defon_close(wsapp):
logger.info("WebSocket closed")
sws.on_open=on_opensws.on_data=on_datasws.on_error=on_errorsws.on_close=on_closesws.connect()fromSmartApi.smartWebSocketOrderUpdateimportSmartWebSocketOrderUpdateclient=SmartWebSocketOrderUpdate(AUTH_TOKEN, API_KEY, CLIENT_CODE, FEED_TOKEN)
client.connect()Check the examples/ folder for ready-to-run scripts:
example_login.ipynb— Generate SmartAPI session with login and TOTPexample_order.ipynb— Place buy/sell orders and manage GTT rulesexample_historical_data.ipynb— Fetch historic candle dataexample_market_data.ipynb— Fetch live market dataexample_websocketV2.ipynb— Connect and subscribe to SmartAPI WebSocket V2
- You need a valid API key and TOTP secret from Angel Broking's developer console.
- Wrap all API calls in try/except blocks to handle errors gracefully.
- Replace placeholders like
"Your Api Key"and"Your client code"with your actual credentials.
Happy Trading! 🚀
