Navigation

    SmartAPI Forum
    • Register
    • Login
    • Search
    • Categories
    • Popular
    • Groups
    • FAQs
    • API Docs

    List of all Smartapi functions in Python

    Python SDK
    8
    11
    1163
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • Mnagesh
      Mnagesh last edited by

      There are around 30 functions provided by SmartApi :

      I am exploring all of them here.

      Thought May be useful for someone.

      if any one need to explore any particular function one can start the new thread in the python group .

      #########################################


      def cancelOrder(self, order_id,variety):
          orderResponse= self._postRequest("api.order.cancel", {"variety": variety,"orderid": order_id})
          return orderResponse
      

      def convertPosition(self,positionParams):
          params=positionParams
          for k in list(params.keys()):
              if params[k] is None:
                  del(params[k])
          convertPositionResponse= self._postRequest("api.convert.position",params)
      
          return convertPositionResponse
      

      def generateSession(self,clientCode,password,totp):
          
          params={"clientcode":clientCode,"password":password,"totp":totp}
          loginResultObject=self._postRequest("api.login",params)
          
          if loginResultObject['status']==True:
              jwtToken=loginResultObject['data']['jwtToken']
              self.setAccessToken(jwtToken)
              refreshToken=loginResultObject['data']['refreshToken']
              feedToken=loginResultObject['data']['feedToken']
              self.setRefreshToken(refreshToken)
              self.setFeedToken(feedToken)
              user=self.getProfile(refreshToken)
          
              id=user['data']['clientcode']
              #id='D88311'
              self.setUserId(id)
              user['data']['jwtToken']="Bearer "+jwtToken
              user['data']['refreshToken']=refreshToken
      
              
              return user
          else:
              return loginResultObject
      

      def generateToken(self,refresh_token):
          response=self._postRequest('api.token',{"refreshToken":refresh_token})
          jwtToken=response['data']['jwtToken']
          feedToken=response['data']['feedToken']
          self.setFeedToken(feedToken)
          self.setAccessToken(jwtToken)
      
          return response
      

      def getCandleData(self,historicDataParams):
          params=historicDataParams
          for k in list(params.keys()):
              if params[k] is None:
                  del(params[k])
          getCandleDataResponse=self._postRequest("api.candle.data",historicDataParams)
          return getCandleDataResponse
      

      def getProfile(self,refreshToken):
          user=self._getRequest("api.user.profile",{"refreshToken":refreshToken})
          return user
      

      def getUserId():
          return userId
      

      def getfeedToken(self):
          return self.feed_token
      

      def gttCancelRule(self,gttCancelParams):
          params=gttCancelParams
          for k in list(params.keys()):
              if params[k] is None:
                  del(params[k])
          
          #print(params)
          cancelGttRuleResponse=self._postRequest("api.gtt.cancel",params)
          #print(cancelGttRuleResponse)
          return cancelGttRuleResponse
      

      def gttCreateRule(self,createRuleParams):
          params=createRuleParams
          for k in list(params.keys()):
              if params[k] is None:
                  del(params[k])
      
          createGttRuleResponse=self._postRequest("api.gtt.create",params)
          #print(createGttRuleResponse)       
          return createGttRuleResponse['data']['id']
      

      def gttDetails(self,id):
          params={
              "id":id
              }
          gttDetailsResponse=self._postRequest("api.gtt.details",params)
          return gttDetailsResponse
      

      def gttLists(self,status,page,count):
          if type(status)== list:
              params={
                  "status":status,
                  "page":page,
                  "count":count
              }
              gttListResponse=self._postRequest("api.gtt.list",params)
              #print(gttListResponse)
              return gttListResponse
          else:
              message="The status param is entered as" +str(type(status))+". Please enter status param as a list i.e., status=['CANCELLED']"
              return message
      

      def gttModifyRule(self,modifyRuleParams):
          params=modifyRuleParams
          for k in list(params.keys()):
              if params[k] is None:
                  del(params[k])
          modifyGttRuleResponse=self._postRequest("api.gtt.modify",params)
          #print(modifyGttRuleResponse)
          return modifyGttRuleResponse['data']['id']
      

      def holding(self):
          holdingResponse= self._getRequest("api.holding")
          return holdingResponse
      

      def login_url(self):
          """Get the remote login url to which a user should be redirected to initiate the login flow."""
          return "%s?api_key=%s" % (self._login_url, self.api_key)
      

      def ltpData(self,exchange,tradingsymbol,symboltoken):
          params={
              "exchange":exchange,
              "tradingsymbol":tradingsymbol,
              "symboltoken":symboltoken
          }
          ltpDataResponse= self._postRequest("api.ltp.data",params)
          return ltpDataResponse
      

      def modifyOrder(self,orderparams):
          params = orderparams
      
          for k in list(params.keys()):
              if params[k] is None:
                  del(params[k])
      
          orderResponse= self._postRequest("api.order.modify", params)
          return orderResponse
      

      def orderBook(self):
          orderBookResponse=self._getRequest("api.order.book")
          return orderBookResponse
      

      def placeOrder(self,orderparams):
      
          params=orderparams
         
          for k in list(params.keys()):
              if params[k] is None :
                  del(params[k])
          
          orderResponse= self._postRequest("api.order.place", params)['data']['orderid']
      
          return orderResponse
      

      def position(self):
          positionResponse= self._getRequest("api.position")
          return positionResponse
      

      def renewAccessToken(self):
          response =self._postRequest('api.refresh', {
              "jwtToken": self.access_token,
              "refreshToken": self.refresh_token,
              
          })
         
          tokenSet={}
      
          if "jwtToken" in response:
              tokenSet['jwtToken']=response['data']['jwtToken']
          tokenSet['clientcode']=self. userId   
          tokenSet['refreshToken']=response['data']["refreshToken"]
         
          return tokenSet
      

      def requestHeaders(self):
          return{
              "Content-type":self.accept,
              "X-ClientLocalIP": self.clientLocalIp,
              "X-ClientPublicIP": self.clientPublicIp,
              "X-MACAddress": self.clientMacAddress,
              "Accept": self.accept,
              "X-PrivateKey": self.privateKey,
              "X-UserType": self.userType,
              "X-SourceID": self.sourceID
          }
      

      def rmsLimit(self):
          rmsLimitResponse= self._getRequest("api.rms.limit")
          return rmsLimitResponse
      

      def setAccessToken(self, access_token):
      
          self.access_token = access_token
      

      def setFeedToken(self,feedToken):
          
          self.feed_token=feedToken
      

      def setRefreshToken(self, refresh_token):
      
          self.refresh_token = refresh_token
      

      def setSessionExpiryHook(self, method):
          if not callable(method):
              raise TypeError("Invalid input type. Only functions are accepted.")
          self.session_expiry_hook = method
      

      def setUserId(self,id):
          self.userId=id
      

      def terminateSession(self,clientCode):
          logoutResponseObject=self._postRequest("api.logout",{"clientcode":clientCode})
          return logoutResponseObject
      

      def tradeBook(self):
          tradeBookResponse=self._getRequest("api.trade.book")
          return tradeBookResponse
      

      Now I am full time Algo Trader and successfully developed my own Apps for my personal use.

      V B P 3 Replies Last reply Reply Quote 1
      • R
        rahul4019 last edited by

        Good thing.
        if possible list down the exceptions that one gets in different apis.
        and most common errors.

        1 Reply Last reply Reply Quote 0
        • V
          Vignesha @Mnagesh last edited by Vignesha

          @Mnagesh Thanks nagesh this deservers a ping so new people can also know this @admin suggest pinging this or add it to your github readme.md file

          Coming to this great work and there are couple of things i wanna ask

          1. I dont see function for live data has this function been stopped?
          2. Does any of the function returns list/number of buyers and sellers and also bid and ask values for equity?
          1 Reply Last reply Reply Quote 0
          • B
            bm0126782 @Mnagesh last edited by

            @Mnagesh Thank you very much.!!

            1 Reply Last reply Reply Quote 0
            • P
              projectSB @Mnagesh last edited by

              @Mnagesh Thanks!
              However, there is an API for getting individual order status. I don't see that mentioned here? Could you please provide that as well?
              OR
              Let's say I have placed an order. How to get the exact status of that individual order? What are my options in this case?
              I want to know whether my order is still pending or complete before placing orders of other legs.

              Mnagesh 1 Reply Last reply Reply Quote 0
              • Mnagesh
                Mnagesh @projectSB last edited by

                @projectSB After getting the order status , you need to search the particular record in JSON so that you will get the result what you need, It is a simple Json extraction .

                Now I am full time Algo Trader and successfully developed my own Apps for my personal use.

                1 Reply Last reply Reply Quote -1
                • R
                  retipser last edited by

                  why is feedtoken fetching some long length hexadecimal code...

                  from SmartApi import SmartConnect,smartApiWebsocket
                  import pandas as pa
                  import xlwings as xl
                  import pyotp as pyo

                  obj=SmartConnect(api_key="*******")
                  data=obj.generateSession("A92018","0409",pyo.TOTP("**************").now())
                  refreshtoken= data['data']['refreshToken']

                  feedtoken = obj.getfeedToken()
                  print(feedtoken)

                  Result : C:\Users\ajays> & C:/Users/ajays/AppData/Local/Microsoft/WindowsApps/python3.12.exe c:/Users/ajays/smartapiv1.py
                  [I 240303 15:21:26 smartConnect:113] in pool
                  eyJhbGciOiJIUzUxMiJ9.eyJ1c2VybmFtZSI6IkE5MjAxOCIsImlhdCI6MTcwOTQ1OTQ4NywiZXhwIjoxNzA5NTQ1ODg3fQ.5mCpr0nNSi19BIwkJSuBEaHvgfYsflipwAGfO4-HupOWFSBGf3_0TSUxw7GX5AaH4uQw0J70Ycg04y_As17o2g

                  1 Reply Last reply Reply Quote 0
                  • Mnagesh
                    Mnagesh last edited by

                    Now around 44 functions are available in Smartapi-python 1.4.8

                    | allholding(self)
                    |
                    | cancelOrder(self, order_id, variety)
                    |
                    | convertPosition(self, positionParams)
                    |
                    | estimateCharges(self, params)
                    |
                    | gainersLosers(self, params)
                    |
                    | generateSession(self, clientCode, password, totp)
                    |
                    | generateTPIN(self, params)
                    |
                    | generateToken(self, refresh_token)
                    |
                    | getCandleData(self, historicDataParams)
                    |
                    | getMarginApi(self, params)
                    |
                    | getMarketData(self, mode, exchangeTokens)
                    |
                    | getProfile(self, refreshToken)
                    |
                    | getTranStatus(self, params)
                    |
                    | getUserId()
                    |
                    | getfeedToken(self)
                    |
                    | gttCancelRule(self, gttCancelParams)
                    |
                    | gttCreateRule(self, createRuleParams)
                    |
                    | gttDetails(self, id)
                    |
                    | gttLists(self, status, page, count)
                    |
                    | gttModifyRule(self, modifyRuleParams)
                    |
                    | holding(self)
                    |
                    | individual_order_details(self, qParam)
                    |
                    | login_url(self)
                    | Get the remote login url to which a user should be redirected to initiate the login flow.
                    |
                    | ltpData(self, exchange, tradingsymbol, symboltoken)
                    |
                    | make_authenticated_get_request(self, url, access_token)
                    |
                    | modifyOrder(self, orderparams)
                    |
                    | oIBuildup(self, params)
                    |
                    | optionGreek(self, params)
                    |
                    | orderBook(self)
                    |
                    | placeOrder(self, orderparams)
                    |
                    | placeOrderFullResponse(self, orderparams)
                    |
                    | position(self)
                    |
                    | putCallRatio(self)
                    |
                    | renewAccessToken(self)
                    |
                    | requestHeaders(self)
                    |
                    | rmsLimit(self)
                    |
                    | searchScrip(self, exchange, searchscrip)
                    |
                    | setAccessToken(self, access_token)
                    |
                    | setFeedToken(self, feedToken)
                    |
                    | setRefreshToken(self, refresh_token)
                    |
                    | setSessionExpiryHook(self, method)
                    |
                    | setUserId(self, id)
                    |
                    | terminateSession(self, clientCode)
                    |
                    | tradeBook(self)
                    |
                    | verifyDis(self, params)

                    Now I am full time Algo Trader and successfully developed my own Apps for my personal use.

                    tester12345 1 Reply Last reply Reply Quote 0
                    • M
                      mrig last edited by

                      how does one get the list of all outstanding gtts in the account. the following is retuning no data while there are actually gtts outstanding in the account

                      smart_api = SmartConnect(api_key=api_key)
                      
                      # Login
                      try:
                          data = smart_api.generateSession(client_code, pwd, totp)
                          print("Login response:", json.dumps(data, indent=2))
                          if data.get('status'):
                              print("Login successful")
                              auth_token = data['data']['jwtToken']
                              refresh_token = data['data']['refreshToken']
                              feed_token = smart_api.getfeedToken()
                              print("Feed token:", feed_token)
                          else:
                              print("Login failed:", data.get('message'))
                              return None
                      except Exception as e:
                          print(f"Login error: {str(e)}")
                          return None
                      
                      # Get the list of GTTs
                      try:
                          # Use the correct method: gttLists
                          gtt_list = smart_api.gttLists(status=['ACTIVE'], page=1, count=10)
                          print("Raw GTT response:", json.dumps(gtt_list, indent=2))
                          
                          if isinstance(gtt_list, dict):
                              if 'status' in gtt_list:
                                  print(f"API Status: {gtt_list['status']}")
                              if 'message' in gtt_list:
                                  print(f"API Message: {gtt_list['message']}")
                              if 'errorcode' in gtt_list:
                                  print(f"API Error Code: {gtt_list['errorcode']}")
                          
                          return gtt_list
                      except Exception as e:
                          print(f"An error occurred while fetching GTT orders: {str(e)}")
                          return None
                      
                      1 Reply Last reply Reply Quote 0
                      • tester12345
                        tester12345 @Mnagesh last edited by

                        @mnagesh https://evil.com

                        tester12345 1 Reply Last reply Reply Quote 0
                        • tester12345
                          tester12345 @tester12345 last edited by

                          @tester12345 https://evil.com

                          P A 2 Replies Last reply Reply Quote 0
                          • First post
                            Last post