Skip to content

Instantly share code, notes, and snippets.

@oldmonkABA
Last active March 3, 2022 16:52
Show Gist options
  • Save oldmonkABA/d5250ba7507c8a3e935ee392a694cfa1 to your computer and use it in GitHub Desktop.
Save oldmonkABA/d5250ba7507c8a3e935ee392a694cfa1 to your computer and use it in GitHub Desktop.
This code demonstrates the automatic process of generating access token for kiteconnect using headless firefox browser
#######################################################################
# Author : Arun B
#
# Purpose : Automate the process of generating access token for kiteconnect in python
############################################################################
# For this code to run you have to download geckodriver and put it in /usr/local/bin
from kiteconnect import KiteConnect,KiteTicker
import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
import re
import json
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.firefox.options import Options
import time
import os
############### Fill in the details of the following section###
kite_api_key = " " #user api_key
kite_api_secret = " " # user api_secret
userid = " " #ZErodha userid
passcode = " " #Zerodha password
zpin = " " #Zerodha pin
################################################################
url = "https://kite.trade/connect/login?v=3&api_key="+kite_api_key
file = kite_api_key+'.json'
if os.path.isfile(file):
print(file+" present in pwd")
with open(file, 'r') as f:
data = json.load(f)
print("Previous login time for "+data["user_name"]+" is "+str(data["login_time"]))
os.remove(file)
print(file+" has been deleted.")
else:
print(file+" does not exist in pwd")
options = Options()
options.headless = True
wd = webdriver.Firefox(options=options)
wd.get(url)
try:
reply = wd.current_url
print(reply)
user_id = "/html/body/div[1]/div/div[2]/div[1]/div/div/div[2]/form/div[1]/input"
password = "/html/body/div[1]/div/div[2]/div[1]/div/div/div[2]/form/div[2]/input"
login_button = "/html/body/div[1]/div/div[2]/div[1]/div/div/div[2]/form/div[4]/button"
pin = "/html/body/div[1]/div/div[2]/div[1]/div/div/div[2]/form/div[2]/div/input"
pin_button = "/html/body/div[1]/div/div[2]/div[1]/div/div/div[2]/form/div[3]/button"
element = element = WebDriverWait(wd, 10).until(
EC.presence_of_element_located((By.XPATH, user_id)))
wd.find_element_by_xpath(user_id).send_keys(userid)
print("Entered USerID")
wd.find_element_by_xpath(password).send_keys(passcode)
print("Entered Password")
wd.find_element_by_xpath(login_button).click()
time.sleep(2)
element = element = WebDriverWait(wd, 10).until(
EC.presence_of_element_located((By.XPATH, pin)))
wd.find_element_by_xpath(pin).send_keys(zpin)
print("Entered PIN")
time.sleep(2)
wd.find_element_by_xpath(pin_button).click()
except Exception as e:
print (e)
time.sleep(5)
reply = wd.current_url
status = re.findall(r'status=(.*)',reply)
print(reply)
if status[0]=="success":
request_token = re.findall(r'request_token=(.*)&action',reply)[0]
kite = KiteConnect(api_key=kite_api_key,disable_ssl=True)
data = kite.generate_session(request_token, api_secret=kite_api_secret)
user_data = json.dumps(data, indent=4, sort_keys=True,default=str)
print(data["user_name"],data["login_time"],data["access_token"])
with open(file, "w") as outfile:
outfile.write(user_data)
time.sleep(5)
print("Automatic login for "+data["user_name"]+" is done. "+file+" has been written to disk")
@GannyS
Copy link

GannyS commented Apr 6, 2020

@oldmonkABA
Copy link
Author

Thank you for pointing the method. But your code does not generate the access token. The whole point of exercise is to generate access token.
Here is the update code of your code : Link

@ankit179
Copy link

When I run this code, it gives the following error:
found = getattr(found, frag)
AttributeError: module 'logmatic' has no attribute 'JsonFormatter'

@oldmonkABA
Copy link
Author

Create a file called logging.json with the following content

{
  "version": 1,
  "disable_existing_loggers": false,
  "formatters": {
    "default": {
      "format": "[%(asctime)s] - [%(levelname)s] - [%(name)s] - [%(funcName)s]:[%(lineno)d] : %(message)s",
      "datefmt":"%Y-%m-%d %H:%M:%S"
    },
    "json": {
      "()": "logmatic.JsonFormatter",
      "format": "[%(asctime)s] - [%(levelname)s] - [%(name)s] - [%(funcName)s]:[%(lineno)d] : %(message)s",
      "datefmt":"%Y-%m-%d %H:%M:%S"
    }
  },
  "handlers": {
    "console": {
      "class": "logging.StreamHandler",
      "level": "DEBUG",
      "formatter": "json"
    },
    "file": {
      "class": "logging.FileHandler",
      "level": "DEBUG",
      "formatter": "json",
      "filename": "logs/output_log.json",
      "mode": "w",
      "encoding": "utf-8"
  }
  },
  "loggers": {
  },
  "root": {
    "level": "INFO",
    "handlers": ["console","file"]
    
  }
}

Create a folder called config within the main directory and move the logging.json into config dir
Then run the code

@Naveenchandra07
Copy link

Hello, thanks for this helpful post. I was able to login successfully using above code. But how can I create kiteconnect ( https://github.com/zerodha/pykiteconnect) object and using it as API trading ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment