Angel Broking Smart API Setup Guide with Full Python API Source [Code]


Angel broking is a big broker which provides trading platforms for different types of trading some user uses their applications some their web interface and some advanced user uses Angel one smart API for their custom algorithms and multiple client order placements.

Today we will provide you with complete code for Angel one smart API Python code. Video for tutorial in Hindi at bottom

1. Open Angel One Account

To do so you need to have Angel one account first you can register from below link or you already have account then there is no need.

2. Register For Angel One SmartAPI

Follow the link below and register yourself for smart API

angel one smart api register

3. Enable TOTP from the top menu and copy 

Generate angel one smart api

4. Create An app to get API from smartapi in angel broking.

Go to My profile > My API > Create an app

create an app in smartapi

Now here you need to fill in information Like

  • Select: Trading
  • App name: anything you want
  • URL :
  • Angel Client ID : Optional

5. Download your Favorite python code editor or use VS Code 

Download python

Download VS Code

In VS code Python will not work directly you need to install Python extension after installing the extension restart your VS code sometimes you need to restart PC.

6. Now Open VS Code terminal in your directory and run these Python commands.

pip install smartapi-python
pip install websocket-client

if the above commands do not work properly and give you errors like

pip : The term 'pip' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, 
verify that the path is correct and try again.

Then try like this

py -m pip install smartapi-python

Just use py -m in the start of your code.

7. To generate TOTP automatically you need to install pyotp

py -m pip install pyotp

Now we are ready to implement Angel One Smart API code.

8. Now we need 2 files 1 for order and 1 for credentials to create 2 files naming and

Here is the Order file code

from smartapi import SmartConnect
import pandas as pd
from datetime import datetime
import credentials
import requests
import numpy as np
import pyotp

myotp =  pyotp.TOTP(credentials.CD).now()

def place_order(token,symbol,qty,exch_seg,buy_sell,ordertype,price):
        orderparams = {
            "variety": "NORMAL",
            "tradingsymbol": symbol,
            "symboltoken": token,
            "transactiontype": buy_sell,
            "exchange": exch_seg,
            "ordertype": ordertype,
            "producttype": "INTRADAY",
            "duration": "DAY",
            "price": price,
            "squareoff": "0",
            "stoploss": "0",
            "quantity": qty
        print("The order id is: {}".format(orderId))
    except Exception as e:
        print("Order placement failed: {}".format(e.message))

def intializeSymbolTokenMap():
    url = ''
    d = requests.get(url).json()
    global token_df
    token_df = pd.DataFrame.from_dict(d)
    token_df['expiry'] = pd.to_datetime(token_df['expiry'])
    token_df = token_df.astype({'strike': float})
    credentials.TOKEN_MAP = token_df

def getTokenInfo (exch_seg, instrumenttype,symbol,strike_price,pe_ce):
    df = credentials.TOKEN_MAP
    strike_price = strike_price*100
    if exch_seg == 'NSE':
        eq_df = df[(df['exch_seg'] == 'NSE') & (df['symbol'].str.contains('EQ')) ]
        return eq_df[eq_df['name'] == symbol]
    elif exch_seg == 'NFO' and ((instrumenttype == 'FUTSTK') or (instrumenttype == 'FUTIDX')):
        return df[(df['exch_seg'] == 'NFO') & (df['instrumenttype'] == instrumenttype) & (df['name'] == symbol)].sort_values(by=['expiry'])
    elif exch_seg == 'NFO' and (instrumenttype == 'OPTSTK' or instrumenttype == 'OPTIDX'):
        return df[(df['exch_seg'] == 'NFO') & (df['instrumenttype'] == instrumenttype) & (df['name'] == symbol) & (df['strike'] == strike_price) & (df['symbol'].str.endswith(pe_ce))].sort_values(by=['expiry'])

if __name__ == '__main__':

data = obj.generateSession(credentials.USER_NAME,credentials.PWD,myotp)
refreshToken= data['data']['refreshToken']
credentials.FEED_TOKEN = feedToken

def userin(): 
    userProfile= obj.getProfile(refreshToken), y=250)  

tokenInfo = getTokenInfo('NFO','OPTIDX','NIFTY',14900,'PE').iloc[0]
symbol  = tokenInfo['symbol']
token = tokenInfo['token']
lot = '100'

#lot = int(tokenInfo['lotsize'])
print(symbol, token, lot)


9. Now create a file and copy your data their

USER_NAME = 's123456'
PWD = '1234'
TOTP = '123456'

10. Sometimes python code doesn’t show and an error it could be because you installed python in your PC user which contains space in their name. Like  c:/users/sandeep kumar/myfolder

Download Files Here



Leave a Reply

Your email address will not be published. Required fields are marked *

Latest comments