Python KiteConnect 3.0 Modules & Functions

def set_access_token(self, access_token):
         """Set the `access_token` received after a successful authentication."""
         self.access_token = access_token

    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&v=3" % (self._default_login_uri, self.api_key)

    def generate_session(self, request_token, api_secret):
         """
         Generate user session details like `access_token` etc by exchanging `request_token`.
         Access token is automatically set if the session is retrieved successfully.

        Do the token exchange with the `request_token` obtained after the login flow,
         and retrieve the `access_token` required for all subsequent requests. The
         response contains not just the `access_token`, but metadata for
         the user who has authenticated.

        - `request_token` is the token obtained from the GET paramers after a successful login redirect.
         - `api_secret` is the API api_secret issued with the API key.
         """
         h = hashlib.sha256(self.api_key.encode("utf-8") + request_token.encode("utf-8") + api_secret.encode("utf-8"))
         checksum = h.hexdigest()

        resp = self._post("api.token", {
             "api_key": self.api_key,
             "request_token": request_token,
             "checksum": checksum
         })

        if "access_token" in resp:
             self.set_access_token(resp["access_token"])

        if resp["login_time"] and len(resp["login_time"]) == 19:
             resp["login_time"] = dateutil.parser.parse(resp["login_time"])

        return resp
    def invalidate_access_token(self, access_token=None):
         """
         Kill the session by invalidating the access token.

        - `access_token` to invalidate. Default is the active `access_token`.
         """
         access_token = access_token or self.access_token
         return self._delete("api.token.invalidate", {
             "api_key": self.api_key,
             "access_token": access_token
         })

    def renew_access_token(self, refresh_token, api_secret):
         """
         Renew expired `refresh_token` using valid `refresh_token`.

        - `refresh_token` is the token obtained from previous successful login flow.
         - `api_secret` is the API api_secret issued with the API key.
         """
         h = hashlib.sha256(self.api_key.encode("utf-8") + refresh_token.encode("utf-8") + api_secret.encode("utf-8"))
         checksum = h.hexdigest()

        resp = self._post("api.token.renew", {
             "api_key": self.api_key,
             "refresh_token": refresh_token,
             "checksum": checksum
         })

        if "access_token" in resp:
             self.set_access_token(resp["access_token"])

        return resp
    def invalidate_refresh_token(self, refresh_token):
         """
         Invalidate refresh token.

        - `refresh_token` is the token which is used to renew access token.
         """
         return self._delete("api.token.invalidate", {
             "api_key": self.api_key,
             "refresh_token": refresh_token
         })

    def margins(self, segment=None):
         """Get account balance and cash margin details for a particular segment.

        - `segment` is the trading segment (eg: equity or commodity)
         """
         if segment:
             return self._get("user.margins.segment", {"segment": segment})
         else:
             return self._get("user.margins")

    def profile(self):
         """Get user profile details."""
         return self._get("user.profile")

    # orders
     def place_order(self,
                     variety,
                     exchange,
                     tradingsymbol,
                     transaction_type,
                     quantity,
                     product,
                     order_type,
                     price=None,
                     validity=None,
                     disclosed_quantity=None,
                     trigger_price=None,
                     squareoff=None,
                     stoploss=None,
                     trailing_stoploss=None,
                     tag=None):
         """Place an order."""
         params = locals()
         del(params["self"])

        for k in list(params.keys()):
             if params[k] is None:
                 del(params[k])

        return self._post("order.place", params)["order_id"]
    def modify_order(self,
                      variety,
                      order_id,
                      parent_order_id=None,
                      quantity=None,
                      price=None,
                      order_type=None,
                      trigger_price=None,
                      validity=None,
                      disclosed_quantity=None):
         """Modify an open order."""
         params = locals()
         del(params["self"])

        for k in list(params.keys()):
             if params[k] is None:
                 del(params[k])

        return self._put("order.modify", params)["order_id"]
    def cancel_order(self, variety, order_id, parent_order_id=None):
         """Cancel an order."""
         return self._delete("order.cancel", {
             "order_id": order_id,
             "variety": variety,
             "parent_order_id": parent_order_id
         })["order_id"]

    def exit_order(self, variety, order_id, parent_order_id=None):
         """Exit a BO/CO order."""
         self.cancel_order(variety, order_id, parent_order_id=parent_order_id)

    def _format_response(self, data):
         """Parse and format responses."""

        if type(data) == list:
             _list = data
         elif type(data) == dict:
             _list = [data]

        for item in _list:
             # Convert date time string to datetime object
             for field in ["order_timestamp", "exchange_timestamp", "created", "last_instalment", "fill_timestamp", "timestamp", "last_trade_time"]:
                 if item.get(field) and len(item[field]) == 19:
                     item[field] = dateutil.parser.parse(item[field])

        return _list[0] if type(data) == dict else _list
    # orderbook and tradebook
     def orders(self):
         """Get list of orders."""
         return self._format_response(self._get("orders"))

    def order_history(self, order_id):
         """
         Get history of individual order.

        - `order_id` is the ID of the order to retrieve order history.
         """
         return self._format_response(self._get("order.info", {"order_id": order_id}))

    def trades(self):
         """
         Retrieve the list of trades executed (all or ones under a particular order).

        An order can be executed in tranches based on market conditions.
         These trades are individually recorded under an order.

        - `order_id` is the ID of the order (optional) whose trades are to be retrieved.
         If no `order_id` is specified, all trades for the day are returned.
         """
         return self._format_response(self._get("trades"))

    def order_trades(self, order_id):
         """
         Retrieve the list of trades executed for a particular order.

        - `order_id` is the ID of the order (optional) whose trades are to be retrieved.
             If no `order_id` is specified, all trades for the day are returned.
         """
         return self._format_response(self._get("order.trades", {"order_id": order_id}))

    def positions(self):
         """Retrieve the list of positions."""
         return self._get("portfolio.positions")

    def holdings(self):
         """Retrieve the list of equity holdings."""
         return self._get("portfolio.holdings")

    def convert_position(self,
                          exchange,
                          tradingsymbol,
                          transaction_type,
                          position_type,
                          quantity,
                          old_product,
                          new_product):
         """Modify an open position's product type."""
         return self._put("portfolio.positions.convert", {
             "exchange": exchange,
             "tradingsymbol": tradingsymbol,
             "transaction_type": transaction_type,
             "position_type": position_type,
             "quantity": quantity,
             "old_product": old_product,
             "new_product": new_product
         })

def instruments(self, exchange=None):
       """
       Retrieve the list of market instruments available to trade.

      Note that the results could be large, several hundred KBs in size,
       with tens of thousands of entries in the list.

      - `exchange` is specific exchange to fetch (Optional)
       """
       if exchange:
           params = {"exchange": exchange}

          return self._parse_instruments(self._get("market.instruments", params))
       else:
           return self._parse_instruments(self._get("market.instruments.all"))

  def quote(self, *instruments):
       """
       Retrieve quote for list of instruments.

      - `instruments` is a list of instruments, Instrument are in the format of `tradingsymbol:exchange`. For example NSE:INFY
       """
       ins = list(instruments)

      # If first element is a list then accept it as instruments list for legacy reason
       if len(instruments) > 0 and type(instruments[0]) == list:
           ins = instruments[0]

      data = self._get("market.quote", {"i": ins})
       return {key: self._format_response(data[key]) for key in data}

  def ohlc(self, *instruments):
       """
       Retrieve OHLC and market depth for list of instruments.

      - `instruments` is a list of instruments, Instrument are in the format of `tradingsymbol:exchange`. For example NSE:INFY
       """
       ins = list(instruments)

      # If first element is a list then accept it as instruments list for legacy reason
       if len(instruments) > 0 and type(instruments[0]) == list:
           ins = instruments[0]

      return self._get("market.quote.ohlc", {"i": ins})
  def ltp(self, *instruments):
       """
       Retrieve last price for list of instruments.

      - `instruments` is a list of instruments, Instrument are in the format of `tradingsymbol:exchange`. For example NSE:INFY
       """
       ins = list(instruments)

      # If first element is a list then accept it as instruments list for legacy reason
       if len(instruments) > 0 and type(instruments[0]) == list:
           ins = instruments[0]

      return self._get("market.quote.ltp", {"i": ins})
  # def instruments_margins(self, segment):
   #     """
   #     Retrive margins provided for individual segments.

  #     `segment` is segment name to retrive.
   #     """
   #     return self._get("market.margins", {"segment": segment})

  def historical_data(self, instrument_token, from_date, to_date, interval, continuous=False):
       """
       Retrieve historical data (candles) for an instrument.

      Although the actual response JSON from the API does not have field
       names such has 'open', 'high' etc., this function call structures
       the data into an array of objects with field names. For example:

      - `instrument_token` is the instrument identifier (retrieved from the instruments()) call.
       - `from_date` is the From date (datetime object or string in format of yyyy-mm-dd HH:MM:SS.
       - `to_date` is the To date (datetime object or string in format of yyyy-mm-dd HH:MM:SS).
       - `interval` is the candle interval (minute, day, 5 minute etc.).
       - `continuous` is a boolean flag to get continuous data for futures and options instruments.
       """
       date_string_format = "%Y-%m-%d %H:%M:%S"
       from_date_string = from_date.strftime(date_string_format) if type(from_date) == datetime.datetime else from_date
       to_date_string = to_date.strftime(date_string_format) if type(to_date) == datetime.datetime else to_date

      data = self._get("market.historical", {
           "instrument_token": instrument_token,
           "from": from_date_string,
           "to": to_date_string,
           "interval": interval,
           "continuous": 1 if continuous else 0
       })

      return self._format_historical(data)
  def _format_historical(self, data):
       records = []
       for d in data["candles"]:
           records.append({
               "date": dateutil.parser.parse(d[0]),
               "open": d[1],
               "high": d[2],
               "low": d[3],
               "close": d[4],
               "volume": d[5]
           })

      return records
  def trigger_range(self, transaction_type, *instruments):
       """Retrieve the buy/sell trigger range for Cover Orders."""
       ins = list(instruments)

      # If first element is a list then accept it as instruments list for legacy reason
       if len(instruments) > 0 and type(instruments[0]) == list:
           ins = instruments[0]

      return self._get("market.trigger_range", {
           "i": ins,
           "transaction_type": transaction_type.lower()
       })