def startsession(): """Saves your login session in the app config folder""" user_id = click.prompt("User ID >") password = click.prompt("Password >", hide_input=True) z = Zerodha() z.user_id = user_id z.password = password j = z.login_step1() if j['status'] == 'error': click.echo(click.style("Error: {}".format(j['message']), fg="red")) return z.twofa = click.prompt("Pin >", hide_input=True) j = z.login_step2(j) if j['status'] == 'error': click.echo(click.style("Error: {}".format(j['message']), fg="red")) return z.enc_token = z.r.cookies['enctoken'] p = z.profile() click.echo( click.style("Logged in successfully as {}".format(p['user_name']), fg='green')) with open(os.path.join(app_dir, session_file), "wb") as fp: pickle.dump(z.reqsession, fp) click.echo("Saved session successfully")
class TestZerodhaLogin(unittest.TestCase): creds = config['CREDENTIALS'] z = Zerodha(creds['user_id'], creds['password'], creds['twofa']) def seq1_login_step1_valid_creds(self): self.step1_result = self.z.login_step1() self.assertEqual(self.step1_result['status'], 'success') def seq2_login_step2_invalid_creds(self): self.z.twofa = "3423122" # random str j = self.z.login_step2(self.step1_result) self.assertEqual(j['status'], 'error') # switch back to original self.z.twofa = self.creds['twofa'] def seq3_login_step2_valid_creds(self): j = self.z.login_step2(self.step1_result) self.assertEqual(j['status'], 'success') self.assertIn('enctoken', self.z.r.cookies) def seq4_login_valid_creds(self): j = self.z.login() self.assertEqual(j['status'], 'success') def seq5_login_invalid_pass(self): self.z.password = "******" with self.assertRaises(Exception): self.z.login() self.z.password = self.creds['password'] def seq6_login_invalid_2fa(self): self.z.twofa = "939344" with self.assertRaises(Exception): self.z.login() self.z.password = self.creds['twofa'] def _steps(self): for name in dir(self): # dir() result is implicitly sorted if name.startswith("seq"): yield name, getattr(self, name) def test_steps(self): click.echo("test-sequence(", nl=False) for i, (_, step) in enumerate(self._steps()): try: step() click.echo("{}".format(i + 1), nl=False) except Exception as e: self.fail("{} failed ({}: {})".format(step, type(e), e)) click.echo(")", nl=False) def test_login_step1_invalid_creds(self): z = Zerodha("randomcreds", "randomstring123324", "2231212") step1_result = z.login_step1() self.assertEqual(step1_result['status'], 'error') z.close() def tearDown(self): self.z.close()
def login(): kite = Zerodha() #kite.set_access_token() kite.load_creds() kite.login() logging.info("Kite Login details") return kite
def main(ticker, interval,duration): #print(instrument, from_, to, interval, output) #ticker="BURGER KING" try: # login() kite = Zerodha() kite.set_access_token() #get dump of all NSE instruments instrument_dump = kite.instruments("NSE") instrument_df = pd.DataFrame(instrument_dump.get("NSE"),columns=["instrument_token", "tradingsymbol", "name", "last_price", "expiry", "strike"]) #instrument_df.to_csv('output.csv',index=False,header=True) instrument = instrument_df[instrument_df['name'].str.contains(ticker, na=False)].tradingsymbol.values[0] instrument = "NSE:"+instrument #instrument = instrumentLookup(instrument_df,ticker) #print(instrument_df) # with open("instruments.csv", 'w') as fp: # writer = csv.DictWriter(fp, ["date", "open", "high", "low", "close", "volume"]) # writer.writeheader() # writer.writerows(instrument_dump.get("NSE")) # #instrument = instrumentLookup(instrument_df,ticker) q = kite.ltp(instrument) token = q[instrument]['instrument_token'] #data = kite.historical_data(token, from_, to, interval) data = pd.DataFrame(kite.historical_data(token,dt.date.today()-dt.timedelta(duration), dt.date.today(),interval)) return data # with open(output, 'w') as fp: # writer = csv.DictWriter(fp, ["date", "open", "high", "low", "close", "volume"]) # writer.writeheader() # writer.writerows(data) except Exception as e: logging.exception("Exception occurred", exc_info=True) print("API error for ticker :",ticker) # if __name__ == "__main__": # main("stock","2020-12-01","2020-12-02","minute")
def start_live_feed(self): self.alice.start_websocket(subscribe_callback=self.get_ltp, socket_open_callback=self.open_callback, run_in_background=True) while (self.socket_opened == False): pass for key in self.ins_exc: self.alice.subscribe( self.alice.get_instrument_by_symbol( self.ins_exc[key]['exchange'], key), LiveFeedType.COMPACT) kite = Zerodha() kite.load_creds() kite.login() if (key[-3:] == 'FUT'): ins_kite = self.ins_exc[key]['exchange'] + ':' + key.split( ' ')[0] + str(datetime.date.today().year)[2:] + key.split( ' ')[1] + key.split(' ')[2] ins_kite_number = kite.quote( ins_kite)[ins_kite]['instrument_token'] from_date = datetime.date.today() - datetime.timedelta(days=5) to_date = datetime.date.today() interval = "minute" self.data[key] = pd.DataFrame( kite.historical_data(ins_kite_number, from_date, to_date, interval, continuous=False, oi=False)) else: ins_kite = self.ins_exc[key]['exchange'] + ':' + key ins_kite_number = kite.quote( ins_kite)[ins_kite]['instrument_token'] from_date = datetime.date.today() - datetime.timedelta(days=5) to_date = datetime.date.today() interval = "minute" self.data[key] = pd.DataFrame( kite.historical_data(ins_kite_number, from_date, to_date, interval, continuous=False, oi=False)) self.data[key]['datetime'] = self.data[key]['date'] self.data[key]['ticker'] = key self.data[key]['date'] = self.data[key]['datetime'].apply( lambda x: x.date()) self.data[key]['time'] = self.data[key]['datetime'].apply( lambda x: x.time()) self.data[key] = self.data[key][[ 'datetime', 'ticker', 'open', 'high', 'low', 'close', 'volume', 'date', 'time' ]] self.data[key]['datetime'] = self.data[key]['date'].apply( str) + self.data[key]['time'].apply(str) self.data[key]['datetime'] = self.data[key]['datetime'].apply( lambda x: datetime.datetime.strptime(x, '%Y-%m-%d%H:%M:%S')) self.data[key].set_index('datetime', inplace=True)
def start_live_feed(self): # Start Alice Blue Websocket and set subscribe callback to get_ltp class method and # socket open callback to open_callback class method self.alice.start_websocket(subscribe_callback=self.get_ltp, socket_open_callback=self.open_callback, run_in_background=True) # Wait and do nothing until socket_opened turns True while(self.socket_opened==False): pass # Create a Zerodha object to get historical data using Jugaad Trader kite = Zerodha() # Automatically load pre-stored credentials kite.load_creds() # Login to Zerodha with loaded credentials kite.login() # Iterate over the keys in instrument_exchange dictionary, which are the instrument names for key in self.instrument_exchange: # Subscribe the particular instrument to alice blue by passing the instrument symbol name and exchange name self.alice.subscribe(self.alice.get_instrument_by_symbol(self.instrument_exchange[key]['exchange'], key), LiveFeedType.COMPACT) # Check if the particular instrument is Futures if (key[-3:] == 'FUT'): # Store the particular instrument in the form Zerodha can extract its token number ins_kite = self.instrument_exchange[key]['exchange'] + ':' + key.split(' ')[0] + str(datetime.date.today().year)[2:] + key.split(' ')[1] + key.split(' ')[2] # Extract the instrument's token number using quote method from Zerodha object ins_kite_number = kite.quote(ins_kite)[ins_kite]['instrument_token'] # If the instrument is not Futures else: # Store the particular instrument in the form Zerodha can extract its token number ins_kite = self.instrument_exchange[key]['exchange'] + ':' + key # Extract the instrument's token number using quote method from Zerodha object ins_kite_number = kite.quote(ins_kite)[ins_kite]['instrument_token'] # Define date from when you want historical data # in this case, it is from 5 days ago from_date = datetime.date.today() - datetime.timedelta(days = 5) # Define date till when you want historical data # in this case, it is until the current time to_date = datetime.date.today() # Define timeframe for the historical data's frequency interval = "minute" # Save historical data to class attribute data and append live resampled data to this eventually self.data[key] = pd.DataFrame(kite.historical_data(ins_kite_number, from_date, to_date, interval, continuous=False, oi=False)) ### Clean the Zerodha historical data to match its format to AliceBlue live data ### # Create datetime column which is equal to the Zerodha historical data's date column self.data[key]['datetime'] = self.data[key]['date'] # Create new column ticker to store symbol name self.data[key]['ticker'] = key # Reassign date column to the date extracted from datetime column self.data[key]['date'] = self.data[key]['datetime'].apply(lambda x : x.date()) # Create time column to the time extracted from datetime column self.data[key]['time'] = self.data[key]['datetime'].apply(lambda x : x.time()) # Reorder column names in the dataframe self.data[key] = self.data[key][['datetime','ticker','open','high','low','close','volume','date','time']] # Reassign datetime column as a combined string form of date and time from the respective columns self.data[key]['datetime'] = self.data[key]['date'].apply(str) + self.data[key]['time'].apply(str) # Set datetime column to datetime format using strptime method self.data[key]['datetime'] = self.data[key]['datetime'].apply(lambda x : datetime.datetime.strptime(x, '%Y-%m-%d%H:%M:%S')) # Set datetime column as index self.data[key].set_index('datetime', inplace=True)
def test_login_step1_invalid_creds(self): z = Zerodha("randomcreds", "randomstring123324", "2231212") step1_result = z.login_step1() self.assertEqual(step1_result['status'], 'error') z.close()
# ----------------------------------------------------------- # ----------------------------------------------------------- ### Save Credentials ### # $ jtrader zerodha savecreds # Saves your creds in app config folder in file named .zcred # User ID >: USERID # Password >: # Pin >: # Saved credentials successfully # Once you have done this, you can call load_creds followed by login. from jugaad_trader import Zerodha kite = Zerodha() kite.load_creds() kite.login() print(kite.profile()) # ----------------------------------------------------------- # ----------------------------------------------------------- ### Config Directory ### # $ jtrader zerodha configdir ###### Delete configuration ###### ### To delete SESSION ###
import pandas as pd from jugaad_trader import Zerodha import KiteSettings user_id = KiteSettings.user_id password = KiteSettings.password two_fa = KiteSettings.two_fa kite = Zerodha(user_id, password, two_fa) # print(kite.login()) # print(kite.profile()) # order_resp = kite.place_order(variety=Zerodha.VARIETY_REGULAR, # tradingsymbol="INFY", # exchange=kite.EXCHANGE_NSE, # transaction_type=kite.TRANSACTION_TYPE_BUY, # quantity="1", # order_type=kite.ORDER_TYPE_MARKET, # product=kite.PRODUCT_CNC) # print(order_resp)
def test_instrument(): z = Zerodha("randomcreds", "randomstring123324", "2231212") instr = z.instruments() assert len(instr) > 100 instr = z.instruments("NSE") assert len(instr) > 100