SMARTAPI-PYTHON is a Python library for interacting with Angel's Trading platform ,that is a set of REST-like HTTP APIs that expose many capabilities required to build stock market investment and trading platforms. It lets you execute orders in real time..
Use the package manager pip to install smartapi-python.
pip install -r requirements_dev.txt # for downloading the other required packagesDownload the following packages
pip install pyotp
pip install logzero
pip install websocket-client For Downloading pycryptodome package
pip uninstall pycrypto
pip install pycryptodome # package import statementfromSmartApiimportSmartConnect#or from SmartApi.smartConnect import SmartConnectimportpyotpfromlogzeroimportloggerapi_key='Your Api Key'username='Your client code'pwd='Your pin'smartApi=SmartConnect(api_key)
try:
token="Your QR value"totp=pyotp.TOTP(token).now()
exceptExceptionase:
logger.error("Invalid Token: The provided token is not valid.")
raiseecorrelation_id="abcde"data=smartApi.generateSession(username, pwd, totp)
ifdata['status'] ==False:
logger.error(data)
else:
# login api call# logger.info(f"You Credentials: {data}")authToken=data['data']['jwtToken']
refreshToken=data['data']['refreshToken']
# fetch the feedtokenfeedToken=smartApi.getfeedToken()
# fetch User Profileres=smartApi.getProfile(refreshToken)
smartApi.generateToken(refreshToken)
res=res['data']['exchanges']
#place ordertry:
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"
}
# Method 1: Place an order and return the order IDorderid=smartApi.placeOrder(orderparams)
logger.info(f"PlaceOrder : {orderid}")
# Method 2: Place an order and return the full responseresponse=smartApi.placeOrderFullResponse(orderparams)
logger.info(f"PlaceOrder : {response}")
exceptExceptionase:
logger.exception(f"Order placement failed: {e}")
#gtt rule creationtry:
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"The GTT rule id is: {rule_id}")
exceptExceptionase:
logger.exception(f"GTT Rule creation failed: {e}")
#gtt rule listtry:
status=["FORALL"] #should be a listpage=1count=10lists=smartApi.gttLists(status,page,count)
exceptExceptionase:
logger.exception(f"GTT Rule List failed: {e}")
#Historic apitry:
historicParam={
"exchange": "NSE",
"symboltoken": "3045",
"interval": "ONE_MINUTE",
"fromdate": "2021-02-08 09:00", "todate": "2021-02-08 09:16"
}
smartApi.getCandleData(historicParam)
exceptExceptionase:
logger.exception(f"Historic Api failed: {e}")
#logouttry:
logout=smartApi.terminateSession('Your Client Id')
logger.info("Logout Successfull")
exceptExceptionase:
logger.exception(f"Logout failed: {e}")
```
## Getting started with SmartAPI Websocket's####### Websocket V2 sample code #######fromSmartApi.smartWebSocketV2importSmartWebSocketV2fromlogzeroimportloggerAUTH_TOKEN="authToken"API_KEY="api_key"CLIENT_CODE="client code"FEED_TOKEN="feedToken"correlation_id="abc123"action=1mode=1token_list= [
{
"exchangeType": 1,
"tokens": ["26009"]
}
]
token_list1= [
{
"action": 0,
"exchangeType": 1,
"tokens": ["26009"]
}
]
sws=SmartWebSocketV2(AUTH_TOKEN, API_KEY, CLIENT_CODE, FEED_TOKEN)
defon_data(wsapp, message):
logger.info("Ticks: {}".format(message))
# close_connection()defon_open(wsapp):
logger.info("on open")
sws.subscribe(correlation_id, mode, token_list)
# sws.unsubscribe(correlation_id, mode, token_list1)defon_error(wsapp, error):
logger.error(error)
defon_close(wsapp):
logger.info("Close")
defclose_connection():
sws.close_connection()
# Assign the callbacks.sws.on_open=on_opensws.on_data=on_datasws.on_error=on_errorsws.on_close=on_closesws.connect()
####### Websocket V2 sample code ENDS Here ################################## SmartWebSocket OrderUpdate Sample Code Start Here ###########################fromSmartApi.smartWebSocketOrderUpdateimportSmartWebSocketOrderUpdateclient=SmartWebSocketOrderUpdate(AUTH_TOKEN, API_KEY, CLIENT_CODE, FEED_TOKEN)
client.connect()
########################### SmartWebSocket OrderUpdate Sample Code End Here #############################Change-log ##1.4.5
- Upgraded TLS Version
##1.4.7
- Added Error log file
##1.4.8
- Intgrated EDIS, Brokerage Calculator, Option Greek, TopGainersLosers, PutRatio API