def get_login(api_k, api_s): global instr,isTickreceived,NFOintr global kws, kite,sripsFortickdata,FOsripsFortickdata kite = KiteConnect(api_key=api_k) print("[*] Generate access Token : ", kite.login_url()) request_tkn = input( "[*]Enter you request tocken here: "); data = kite.generate_session(request_tkn, api_secret=api_s ) kite.set_access_token(data["access_token"]) kws = KiteTicker(api_k, data["access_token"]) instr = kite.instruments("NSE") NFOintr = kite.instruments("NFO") print(len(instr)) '''for scrip in instr: print(scrip['tradingsymbol'])''' df = pd.read_csv("D:\\Dev_Folder\\BankNifty.csv",usecols=['stocks', 'weightage']) df['instrument_token'] = df['stocks'].apply(getInstrumentToken) df['FOinstrument_token'] = df['stocks'].apply(getFOInstrumentToken) df['LotSize'] = df['stocks'].apply(getLotSize) for index, row in df.iterrows(): #print (row["stocks"], row["instrument_token"]) sripsFortickdata.append(row["instrument_token"]) sripsweightage.append(row["weightage"]) FOsripsFortickdata.append(row["FOinstrument_token"]) Lot_Size.append(row["LotSize"]) #sripsFortickdata = df['instrument_token'][:] #print(sripsFortickdata) '''x=0
def index(request): ctx = {} ctx['access_token'] = request.session.get('access_token', '') if ctx['access_token']: kite = KiteConnect(api_key=api_key) kite.set_access_token(ctx['access_token']) ctx['orders'] = kite.instruments()[:10] return render(request, "main/index.html", ctx)
def main(): #print("ddf") #zerodha_access_token = [] wb = load_workbook('zerotha_scanner.xlsx') ws1 = wb["zerotha_scanner"] data = ws1.values # Get the first line in file as a header line columns = next(data)[0:] # Create a DataFrame based on the second and subsequent lines of data df1 = pd.DataFrame(data, columns=columns) ''' ws2 = wb["Sheet2"] data = ws2.values # Get the first line in file as a header line columns = next(data)[0:] # Create a DataFrame based on the second and subsequent lines of data df2 = pd.DataFrame(data, columns=columns)''' #df1=pd.read_excel("zerotha_scanner.xlsx") df2 = pd.read_csv("zerotha_scanner_credentials.csv") print(df1) print(df2) zerodha = ZerodhaAccessToken(df2.iloc[0, 0], df2.iloc[0, 1], df2.iloc[0, 4], df2.iloc[0, 2], df2.iloc[0, 3]) access_token = zerodha.getaccesstoken() kite = KiteConnect(api_key=df2.iloc[0, 0]) kite.set_access_token(access_token) print(access_token) #zerodha_access_token.append(access_token) #kite=ClientZerodha(api_key = 6zfi2amoxjco04yo, zerodha_id = RP7365, kite = kite,multiplier = multiplier, api_secret = p2zkzvivv3y8fveacsb9ciqnu5y71iul, pin = 244280,access_token = access_token, password = chicu24428) instruments = kite.instruments() #print(instruments) symbol = [] tracker_token = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for i in range(df1.shape[0]): symbol.append(df1.iloc[i, 0]) print(symbol) for instrument in instruments: for i in range(df1.shape[0]): if instrument['tradingsymbol'] == symbol[i]: tracker_token[i] = instrument['instrument_token'] elif tracker_token[i] == 0: tracker_token[i] = 1 print(tracker_token) tracker_token[:] = (value for value in tracker_token if value != 0) print(tracker_token) count = 0 for i in tracker_token: if i == 1: print(df1.iloc[count, 0], "tracker token doesnt exist") count += 1 tracker_token[:] = (value for value in tracker_token if value != 1) return kite, access_token, tracker_token, instruments, df1, df2
class MyKite: def __init__(self): # Get the request token try: request_token = Get_Request_Token() self.kite = KiteConnect(config.api_key, config.secret_key) data = self.kite.request_access_token(request_token, config.secret_key) self.kite.set_access_token(data["access_token"]) self.public_token = data["public_token"] except: lg.error("Error in kite connection") exit() # Place an order to kite def order(self, scrip, bs, qty): try: order_id = self.kite.order_place(tradingsymbol=scrip, \ exchange=config.exchange, \ transaction_type=bs, \ quantity=qty, \ order_type="MARKET", \ product=config.Product) lg.debug("Order:%s, %s, %s, %s", order_id, scrip, bs, qty) except Exception as e: lg.error("Kite Order placement failed.") return (order_id) #get a list of instruments from Kite def get_instr(self): try: return (self.kite.instruments()) except Exception as e: lg.error("Kite Get instruments failed.") return ([]) def order_cancle(self, order_id): try: self.kite.order_cancel(order_id="order_id") except Exception as e: lg.error("Kite Order %s cancle failed.", order_id) def get_orders(self): try: return (self.kite.orders()) except Exception as e: lg.error("Kite Get Order status failed.") def get_public_token(self): return (self.public_token)
class kiteparse: def __init__(self): self.kite = KiteConnect(api_key="2x2f2a8447agu452") print(self.kite.login_url()) access_token = input("Enter token:") data = self.kite.generate_session(access_token, api_secret="kfygfd0sgae19vnmsz49pnd1t44dacb1") self.kite.set_access_token(data["access_token"]) data = self.kite.instruments() self.df = pd.DataFrame(data)[["instrument_token","exchange_token","tradingsymbol","exchange"]] def read_data_backtest(self, symbol_1, interval, exchange="NSE", symbol=True, days=0): instrument = symbol_1 if symbol: dat = self.df.loc[self.df['tradingsymbol'] == symbol_1 , ['exchange','instrument_token']] instrument = dat.loc[dat['exchange'] == exchange, 'instrument_token'].iloc[0] tzinfo = pytz.timezone('Asia/Kolkata') now = datetime.now(tz= tzinfo)#tz= tzinf today = now.date() current_time = time(now.hour, now.minute, now.second) # print(current_time,today, today.weekday()) to_d = datetime.combine(today, current_time)) from_d = datetime.combine(today-timedelta(days=days), time(9, 15, 00))) #from_d = datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) ohlcv = pd.DataFrame(self.kite.historical_data(instrument_token=instrument,from_date=from_d,to_date=to_d,interval=interval)) return ohlcv, to_d def placeorder(self,item, exchange, action, quantity): try: order_id = self.kite.place_order(tradingsymbol=item, exchange=exchange, transaction_type=action, quantity=quantity, variety="regular", order_type="MARKET", product="MIS") logging.info("Order placed. ID is: {}".format(order_id)) except Exception as e: print(e)
class Configurator(object): def __init__(self, driver_path=None): # lazy evaluate the driver inside the get_config and kill it by the end driver = Driver() with driver as d: single_auth = AuthSingletonStack.pop() self.api_key = single_auth["api_key"] self.secret_key = single_auth["secret_key"] self.u_id = single_auth["u_id"] self.password = single_auth["password"] self.kite = KiteConnect(self.api_key, self.secret_key) # Hit the first url and get session_id d.get(self.kite.login_url()) self.session_id = driver.parse_url("sess_id") # login to first auth page user_id = d.find_elements_by_tag_name("input")[0] pwd = d.find_elements_by_tag_name("input")[1] login = d.find_element_by_xpath('//button[@type="submit"]') user_id.send_keys(self.u_id) pwd.send_keys(self.password) login.click() # Wait for second auth page to load and fill the second factor authentication question time.sleep(15) driver.fill_second_factor_auth_question(0) driver.fill_second_factor_auth_question(1) login.click() # return request token from final url self.request_token = driver.parse_url("request_token") self.data = self.kite.generate_session( api_secret=self.secret_key, request_token=self.request_token) self.access_token = self.data["access_token"] self.public_token = self.data["public_token"] self.user_id = self.data["user_id"] self.nfo = self.kite.instruments("NFO")
if y['mean_value'] > 1.5 * average_mean_value and y[ 'mean_price'] > 25: updated.append(y) print(updated) tradable_df = pd.DataFrame(updated) tradable_df['margin'] = tradable_df['mis_multiplier'] tradable_df['symbol'] = tradable_df['tradingsymbol'] tradable_df = tradable_df[['instrument_token', 'symbol', 'margin']] tradable_df.to_csv('tradables.csv') access_token = 'wRW31cTjmI3RmZBrrFf1Pg3C18MiexXe' api_key = '7lwrah449p8wk3i0' kite = KiteConnect(api_key=api_key) kite.set_access_token(access_token=access_token) instrument_list = pd.DataFrame(kite.instruments(exchange=kite.EXCHANGE_NSE)) instrument_list = instrument_list[instrument_list['segment'] == 'NSE'] instrument_list = instrument_list.set_index('tradingsymbol') http = urllib3.PoolManager() r = http.request('GET', 'https://api.kite.trade/margins/equity') margins = pd.DataFrame(json.loads(r.data.decode('utf-8'))) margins = margins.set_index('tradingsymbol') joined_df = pd.concat([instrument_list, margins], axis=1, join='inner') joined_df = joined_df[['instrument_token', 'mis_multiplier']] joined_df = joined_df.reset_index() joined_df.to_csv('full_list.csv') from_date = datetime.date.today() + datetime.timedelta(-30) to_date = datetime.date.today() print(from_date, to_date)
order_id = kite.place_order(tradingsymbol="INFY", exchange=kite.EXCHANGE_NSE, transaction_type=kite.TRANSACTION_TYPE_BUY, quantity=1, order_type=kite.ORDER_TYPE_MARKET, product=kite.PRODUCT_NRML) logging.info("Order placed. ID is: {}".format(order_id)) except Exception as e: logging.info("Order placement failed: {}".format(e.message)) # Fetch all orders kite.orders() # Get instruments kite.instruments() # Place an mutual fund order kite.place_mf_order(tradingsymbol="INF090I01239", transaction_type=kite.TRANSACTION_TYPE_BUY, amount=5000, tag="mytag") # Cancel a mutual fund order kite.cancel_mf_order(order_id="order_id") # Get mutual fund instruments kite.mf_instruments() ## WebSocket Usage
api_key = 'd1zkjgaordrrjgis' api_secret = 'owe9bi50r9f8lr71jvvqesm5m86p1emf' request_token = 'lv4C6NnXWKzO0vJpr7Ng6TuKY1yeER75' access_token = 'uI19de8AKzQKqjToZWKO6Y7gkLC4pe8x' public_token = 'ceWhjfvd6dW5doZ2ug5dtDxdLgtTOkov' kite = KiteConnect(api_key=api_key) #print(kite.login_url()) #https://kite.trade/connect/login?api_key=d1zkjgaordrrjgis&v=3 #data = kite.generate_session(request_token, api_secret=api_secret) #access_token=data['access_token'] #public_token= data['public_token'] kite.set_access_token(access_token) inst = kite.instruments('MCX') symbols_codes = {} symbols = ["CRUDEOIL18NOVFUT"] symbol_tokens = [] for i in range(len(inst)): for j in range(len(symbols)): if inst[i]['tradingsymbol'] == symbols[j]: symbols_codes.update({ inst[i]['tradingsymbol']: { 'tradingsymbol': inst[i]['tradingsymbol'], 'instrument_token': inst[i]['instrument_token'], 'last_price': [], 'oi': [], 'vol': [],
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 10 15:57:23 2020 @author: saravana.kumar """ from kiteconnect import KiteConnect import logging import os import pandas as pd cwd = os.chdir("/Users/saravana.kumar/Downloads/Personal/doalgo/zerodha/") #generate trading session access_token = open("access_token.txt", 'r').read() key_secret = open("api_key.txt", 'r').read().split() kite = KiteConnect(api_key=key_secret[0]) kite.set_access_token(access_token) instrument_dump = kite.instruments('NSE') instrument_df = pd.DataFrame(instrument_dump) values = instrument_df[instrument_df.tradingsymbol == 'INFY'].instrument_token.values[0]
class InstrumentMaster: def __init__(self, api_key): self.fno_file = 'https://archives.nseindia.com/content/fo/fo_mktlots.csv' self.kite = KiteConnect(api_key=api_key) self.headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36' } self.redis_db = InstrumentDumpFetch() def filter_redis_dump(self): """ Filter only option contract from master instrument and dump it to redis """ contractToken = {} result = None # Fetch instrument file # Filter only F&O contracts instruments = self.kite.instruments('NFO') # Dump token:{symbol,strike} data to redis for contract in instruments: token_detail = { 'symbol': contract['tradingsymbol'], 'strike': contract['strike'], 'type': contract['instrument_type'], 'name': contract['name'] } self.redis_db.data_dump(contract['instrument_token'], token_detail) # Download and read F&O enabled list of contract response = requests.get(self.fno_file, headers=self.headers) with open(os.path.join('fo_mktlots.csv'), 'wb') as f: f.write(response.content) # Filter only contract symbol from marketlot file fno_contract = pd.read_csv('fo_mktlots.csv') optionInstrument = [] for index, row in fno_contract.iterrows(): optionInstrument.append(row['SYMBOL '].rstrip()) for optContract in optionInstrument: # Create list of strike price for specific symbol contractToken[optContract] = [] for contract in instruments: if contract['name'] == optContract and \ contract['segment'] == 'NFO-OPT': contractToken[optContract].append({ 'strike': contract['strike'], 'type': contract['instrument_type'], 'expiry': str(contract['expiry']), 'token': contract['instrument_token'] }) self.redis_db.data_dump(optContract, contractToken[optContract]) def fetch_contract(self, symbol, expiry): """ Fetch strike and token detail for requested symbol Param symbol:(string) - Option contract symbol """ token_list = [] optionData = self.redis_db.symbol_data(symbol) for strike_detail in optionData: if strike_detail['expiry'] == str(expiry): token_list.append(strike_detail['token']) return token_list def fetch_token_detail(self, token): """ Fetch contract name for requested instrument token Param token:(integer) - Instrument token """ return self.redis_db.fetch_token(token) def store_option_data(self, tradingsymbol, token, optionData): """ Store option chain data for requested symbol Param tradingsymbol:(string) - Option contract symbol Param token:(string) - Expiry date of the requested symbol Param optionData:(string) - Complete data dump for required option symbol """ return self.redis_db.store_optiondata(tradingsymbol, token, optionData) def generate_optionChain(self, token_list): """ Fetch all option contracts for requested symbol Param token:(List of string) - List of token """ optionChain = [] # Iterate though list of tokens for respective symbol and fetch respective strike data for instrumentToken in token_list: # Fetch market depth data for respective strike optionInstrument = self.fetch_token_detail(instrumentToken) optionData = self.redis_db.fetch_option_data( optionInstrument['symbol'], instrumentToken) optionChain.append(optionData) return optionChain
#print(kite.ltp(256265)) #inst=kite.instruments('NFO') ##############################################TICKER################################################### class var(): tc = 0 ticks = {} inst_index = [256265, 260105] #inst_all=[14512130,14514690,14517762,14598658,14605058,14512386,14515970,14518018,14598914,14607362,12438530,12434434,311555,368643,370947] inst_all = [311555, 368643, 370947] data = {} inst = kite.instruments('CDS') for i in range(len(inst)): for j in range(len(var.inst_all)): if inst[i]['instrument_token'] == var.inst_all[j]: var.data.update({ inst[i]['tradingsymbol']: { 'tradingsymbol': inst[i]['tradingsymbol'], 'instrument_token': inst[i]['instrument_token'], 'last_price': [], 'oi': [], 'vol': [], 'buy_quantity': [], 'sell_quantity': [], 'ltq': [] } })
import json import pdb import utilities as util from yahoo_finance_api import YahooFinance as yf import strategy as st from pytz import timezone import asyncio import orders as ord # Enter the user api_key and the access_token generated for that day credentials = {'api_key': util.api_key, 'access_token': util.access_token} kite = KiteConnect(api_key=credentials['api_key']) kite.set_access_token(credentials['access_token']) inst_list = kite.instruments('NSE') infy_rec = util.get_instrument_details_by_name('INFY', inst_list) sbin_rec = util.get_instrument_details_by_name('SBIN', inst_list) sbin1m = yf('SBIN.NS', result_range='1d', interval='1m', dropna='True').result sbin5m = yf('SBIN.NS', result_range='1d', interval='5m', dropna='True').result print(sbin1m.tail()) print(sbin5m.tail()) sbin1m = sbin1m[:-1] sbin5m = sbin5m[:-1] print(' ---------------- After removing last row ------------------') print(sbin1m.tail()) print(sbin5m.tail()) """
class LiveSimulator: def __init__(self, api_key=Config.KITE_API_KEY, api_secret=Config.KITE_API_SECRET, username = Config.KITE_USER_ID, password=Config.KITE_PASSWORD, pin=Config.KITE_PIN, end_hour=Config.KITE_SIMULATION_END_HOUR, end_minute=Config.KITE_SIMULATION_END_MINUTE): self.username = username self.password = password self.pin = pin # TODO: Generate kite instance only when a function that requires it is called self.api_key = api_key self.kite = KiteConnect(api_key=api_key) req_token = self.get_request_token() data = self.kite.generate_session(req_token, api_secret=api_secret) self.access_token = data["access_token"] self.kite.set_access_token(self.access_token) self.kite_state = list(KiteSimulatorStateModel.objects.raw({'createdDate': str(date.today())}))[-1] self.end_time = datetime.now().astimezone(tzlocal()).replace(hour=end_hour, minute=end_minute) def get_instrument_tokens(self, instrument_list: list): instrument_token_list = dict() self.instrument_infos = self.kite.instruments(exchange='NSE') for instrument in instrument_list: for instrument_info in self.instrument_infos: if instrument == instrument_info['tradingsymbol']: instrument_token_list[instrument] = instrument_info['instrument_token'] break return instrument_token_list def sim_init(self): if not self.kite_state.simulationInitSuccessful: # Initialise ticker = KiteTicker(self.api_key, self.access_token) instrument_tokens = self.kite_state.companyTokens.copy() profit_slab = self.kite_state.profitSlab buy_dict = dict() # Defining the callbacks def on_ticks(tick, ticks_info): # global buy_dict for tick_info in ticks_info: # TODO : Check if the order is correct buy_dict[tick_info['instrument_token']] = tick_info['depth']['sell'][0]['price'] tick.close() def on_connect(tick, response): # global instrument_tokens tick.subscribe(self.kite_state.companyTokens) tick.set_mode(tick.MODE_FULL, self.kite_state.companyTokens) def on_close(tick, code, reason): tick.stop() Logger.info('Connection closed successfully!') # Assign the callbacks. ticker.on_ticks = on_ticks ticker.on_connect = on_connect ticker.on_close = on_close ticker.connect() # Building buy list buy_list = list() for token in instrument_tokens: buy_list.append(buy_dict[token]) final_buy_list = list() for buy, low in zip(buy_list, self.kite_state.lowPrice): if buy < 1: final_buy_list.append(low) else: final_buy_list.append(buy) self.kite_state.buyPrice = final_buy_list # TODO: Round off all calculations like this upto 2 decimal places, perfectly divisible by 0.05 self.kite_state.profitablePrice = (np.array(final_buy_list) + np.array(self.kite_state.profitSlab)).tolist() self.kite_state.simulationInitSuccessful = True self.kite_state.save() def simulate_market(self): # Initialise ticker = KiteTicker(self.api_key, self.access_token) instrument_tokens = self.kite_state.companyTokens.copy() profitable_prices = self.kite_state.profitablePrice.copy() sell_dict = dict() price_state_dict = dict() profitable_dict = dict() first_tick = False # Building profitable dict for token, profitable_price in zip(instrument_tokens, profitable_prices): profitable_dict[token] = profitable_price # Defining the callbacks def on_ticks(tick, ticks_info): if len(instrument_tokens) == 0: tick.close() num_ticks = len(ticks_info) Logger.info('Ticking, number: {}'.format(num_ticks)) now = datetime.now().astimezone(tzlocal()) if num_ticks > 0: if now < self.end_time: Logger.info('Normal Time:->' + now.strftime("%H:%M:%S")) for tick_info in ticks_info: current_instrument_token = tick_info['instrument_token'] current_instrument_price = tick_info['depth']['buy'][0]['price'] price_state_dict[current_instrument_token] = current_instrument_price if current_instrument_price >= profitable_dict[current_instrument_token]: sell_dict[current_instrument_token] = current_instrument_price tick.unsubscribe([current_instrument_token]) instrument_tokens.remove(current_instrument_token) # tick.resubscribe() Logger.info('Unsubscribed token: ' + str(current_instrument_token)) else: Logger.info('Closing Time:->' + now.strftime("%H:%M:%S")) Logger.info('Price State dict: ' + str(price_state_dict)) Logger.info('Sell dict: ' + str(sell_dict)) unsold_instrument_tokens = list(set(price_state_dict.keys()) - set(sell_dict.keys())) Logger.info('Unsold instruments: ' + str(unsold_instrument_tokens)) for instrument_token in unsold_instrument_tokens: sell_dict[instrument_token] = price_state_dict[instrument_token] instrument_tokens.remove(instrument_token) Logger.info('Sell dict after close: ' + str(sell_dict)) def on_connect(tick, response): tick.subscribe(instrument_tokens) tick.set_mode(tick.MODE_FULL, instrument_tokens) Logger.info('Subscribed tokens: ' + str(instrument_tokens)) def on_close(tick, code, reason): Logger.info('Ticker closed successfuly!') tick.stop() # Assign the callbacks. ticker.on_ticks = on_ticks ticker.on_connect = on_connect ticker.on_close = on_close # Connect to live ticker # if not ticker.is_connected(): ticker.connect() Logger.info('Building final dict' + str(sell_dict)) # Build final sell_dict in correct order sell_list = list() for key in profitable_dict.keys(): try: sell_list.append(sell_dict[key]) except KeyError as ex: Logger.err('Key error' + str(ex)) # TODO: Make this failsafe more robust sell_list.append(0) self.kite_state.sellPrice = sell_list self.kite_state.save() def calculate_and_store_pnl(self): quantitiy = np.array(self.kite_state.numberOfStocksPerCompany) # Subtracting 1 from all companies as a failsafe for fund exhaustion, in case the stocks goes really high normalised_quantity = quantitiy - 1 # Rounding negative values to 0 normalised_quantity = normalised_quantity.clip(min=0) buy = np.array(self.kite_state.buyPrice) sell = np.array(self.kite_state.sellPrice) pnl_per_company = np.multiply(sell - buy, normalised_quantity) self.kite_state.pnlPerCompany = pnl_per_company.tolist() self.kite_state.pnl = float(np.sum(pnl_per_company)) self.kite_state.save() Logger.info("Today's PNL: {}".format(self.kite_state.pnl), push_to_slack=True) def get_request_token(self): Logger.info('Starting to fetch request token for Kite API') selenium = SeleniumDispatcher(headless=True) driver = selenium.get_driver() driver.get(self.kite.login_url()) time.sleep(4) username_field = driver.find_element_by_xpath("//input[@type='text']") username_field.send_keys(self.username) password_field = driver.find_element_by_xpath("//input[@type='password']") password_field.send_keys(self.password) password_field.send_keys(Keys.ENTER) time.sleep(2) pin_field = driver.find_element_by_xpath("//input[@type='password']") pin_field.send_keys(self.pin) pin_field.send_keys(Keys.ENTER) time.sleep(2) url = driver.current_url parsed = urlparse.urlparse(url) token = parse_qs(parsed.query)['request_token'][0] Logger.info('Request token received!') selenium.destroy_driver() return token
from kiteconnect import KiteConnect #tradingsymbol:NIFTY18OCTFUT,instrument_token: 12438530 # index : NIFTY 50, instrument_token: 256265 #tradingsymbol:BANKNIFTY18OCTFUT, instrument_token: 12434434 #index : NIFTYBANK,instrument_token: 260105 #NIFTY18OCT10500CE :14517762 , NIFTY18OCT10500PE:14518018, CRUDEOIL18OCTFUT: 53835015 api_key='d1zkjgaordrrjgis' api_secret='owe9bi50r9f8lr71jvvqesm5m86p1emf' kite=KiteConnect(api_key=api_key) inst=kite.instruments('NFO') print(inst) for i in range(len(inst)): if(inst[i]['instrument_type']=='FUT' and inst[i]['lot_size']==75) :print(inst[i]) for i in range(len(inst)): if(inst[i]['tradingsymbol']=='NIFTY 50':print(inst[i])
def option_chain(token): kite = KiteConnect(api_key="XXXXXXXXXXX") kite.set_access_token(token["access_token"]) response = kite.instruments() number = 1 for values in response: """ Storing the contract of banknifty """ if (values['tradingsymbol'][0:9] == "BANKNIFTY"): #November month bank nifty contract #Checking the required common nomenclature for option contract and saving to DB if (values['tradingsymbol'][9:14] == "17NOV"): #storing CE and PE option contract in different database if (values['tradingsymbol'][-2:] == "CE"): feeding = Instruments( banknifty_latest_call=values['tradingsymbol'], banknifty_latestce_token=values['instrument_token'] ) feeding.save() number = number + 1 if (values['tradingsymbol'][-2:] == "PE"): feeding = Instruments( banknifty_latest_put=values['tradingsymbol'], banknifty_latestpe_token=values['instrument_token'] ) feeding.save() number = number + 1 #December month bank nifty contract if (values['tradingsymbol'][9:14] == "17DEC"): #storing CE and PE option contract in different database if (values['tradingsymbol'][-2:] == "CE"): feeding = Instruments( banknifty_next_call=values['tradingsymbol'], banknifty_nextce_token=values['instrument_token']) feeding.save() number = number + 1 if (values['tradingsymbol'][-2:] == "PE"): feeding = Instruments( banknifty_next_put=values['tradingsymbol'], banknifty_nextpe_token=values['instrument_token']) feeding.save() number = number + 1 #18January bank nifty contract if (values['tradingsymbol'][9:14] == "18JAN"): if (values['tradingsymbol'][-2:] == "CE"): feeding = Instruments( banknifty_last_call=values['tradingsymbol'], banknifty_lastce_token=values['instrument_token']) feeding.save() if (values['tradingsymbol'][-2:] == "PE"): feeding = Instruments( banknifty_last_put=values['tradingsymbol'], banknifty_lastpe_token=values['instrument_token']) feeding.save() """ Storing the Nifty contract """ if (values['tradingsymbol'][0:5] == "NIFTY"): # November month nifty contract if (values['tradingsymbol'][5:10] == "17NOV"): if (values['tradingsymbol'][-2:] == "CE"): feeding = Instruments( nifty_latest_call=values['tradingsymbol'], nifty_latestce_token=values['instrument_token']) feeding.save() number = number + 1 if (values['tradingsymbol'][-2:] == "PE"): feeding = Instruments( nifty_latest_put=values['tradingsymbol'], nifty_latestpe_token=values['instrument_token']) feeding.save() number = number + 1 # December month nifty contract if (values['tradingsymbol'][5:10] == "17DEC"): if (values['tradingsymbol'][-2:] == "CE"): feeding = Instruments( nifty_next_call=values['tradingsymbol'], nifty_nextce_token=values['instrument_token']) feeding.save() number = number + 1 if (values['tradingsymbol'][-2:] == "PE"): feeding = Instruments( nifty_next_put=values['tradingsymbol'], nifty_nextpe_token=values['instrument_token']) feeding.save() number = number + 1 # 18January month nifty contract if (values['tradingsymbol'][5:10] == "18JAN"): if (values['tradingsymbol'][-2:] == "CE"): feeding = Instruments( nifty_last_call=values['tradingsymbol'], nifty_lastce_token=values['instrument_token']) feeding.save() number = number + 1 if (values['tradingsymbol'][-2:] == "PE"): feeding = Instruments( nifty_last_put=values['tradingsymbol'], nifty_lastpe_token=values['instrument_token']) feeding.save() number = number + 1 return HttpResponse('<h2>Data is synced</h2>')
Algorithmic trading module for NSE-India via pykiteconnect & zerodha ''' #Importing necessary libraries import webbrowser as wb import pandas as pd from kiteconnect import KiteConnect, WebSocket #api_key,api_secret,user_id given by zerodha #store it in the working directory in a file called credential api_key, api_secret, user_id = open('credential', 'r+').read().strip('\n').split(',') kite = KiteConnect(api_key=api_key) login_url = kite.login_url() wb.open(login_url) #Get the request token after login from webbrowser and put the token here request_token = '' auth_data = kite.request_access_token(request_token, secret=api_secret) access_token = auth_data["access_token"] public_token = auth_data["public_token"] kite.set_access_token(access_token) with open('auth_data.txt', 'r+') as f: f.write(access_token + ',' + public_token) #Retrieve instruments token instrument = kite.instruments() instrument = pd.DataFrame(instrument) #Saving to local file instrument.to_csv('instrument.csv')
class Zerodha(Broker): """ Automated Trading class """ def __init__( self, api_key, secret, user_id, password, PIN, exchange="NSE", product="MIS", totp=None, is_pin=False, ): self._api_key = api_key self._secret = secret self._user_id = user_id self._password = password self._pin = PIN self._totp = totp self.is_pin = is_pin self.exchange = exchange self.product = product self._store_access_token = True super(Zerodha, self).__init__() @property def isNilPositions(self): """ return True if there are no open positions else return False """ temp = pd.DataFrame(self.positions()["net"]) if temp.quantity.abs().sum() == 0: return True else: return False @property def isNilPositionsDay(self): """ return True if there are no open positions for the day else return False """ temp = pd.DataFrame(self.positions()["day"]) if temp.quantity.abs().sum() == 0: return True else: return False @property def isNilOrders(self): """ return True if there are no pending orders else return False """ pending = [ o for o in self.orders() if o.get("status", "PENDING") == "PENDING" ] if len(pending) == 0: return True else: return False def cancel_all_orders(self, retries=5): """ Cancel all existing orders """ for o in self.orders(): try: if o["status"] == "PENDING": self.order_cancel( variety=o["variety"], order_id=o["order_id"], parent_order_id=o["parent_order_id"], ) except Exception as e: print(e) i = 0 while not (self.isNilOrders): print("Into the loop") i += 1 for o in self.orders(): try: if o["status"] == "PENDING": self.order_cancel( variety=o["variety"], order_id=o["order_id"], parent_order_id=o["parent_order_id"], ) except Exception as e: print(e) if i > retries: print("Breaking out of loop without canceling all orders") break def _shortcuts(self): """ Provides shortcuts to kite functions by mapping functions. Instead of calling at.kite.quote, you would directly call at.quote Note ----- 1) Kite functions are initialized only after authentication 1) Not all functions are supported """ self.margins = self.kite.margins self.profile = self.kite.profile self.ltp = self.kite.ltp self.quote = self.kite.quote self.ohlc = self.kite.ohlc self.trades = self.kite.trades self.holdings = self.kite.holdings self._sides = {"BUY": "SELL", "SELL": "BUY"} def authenticate(self): """ Authenticates a kite session if access token is already available Looks up token in token.tok file Useful for reconnecting instead of logging in again """ try: self.kite = KiteConnect(api_key=self._api_key) with open("token.tok") as f: access_token = f.read() self.kite.set_access_token(access_token) self.kite.profile() self.ticker = KiteTicker(api_key=self._api_key, access_token=self.kite.access_token) self._shortcuts() except TokenException: print("Into Exception") self._login() self._shortcuts() self.ticker = KiteTicker(api_key=self._api_key, access_token=self.kite.access_token) except: print("Unknown Exception") self._login() self._shortcuts() self.ticker = KiteTicker(api_key=self._api_key, access_token=self.kite.access_token) def _login(self): import time self.kite = KiteConnect(api_key=self._api_key) options = Options() options.add_argument("--headless") options.add_argument("--disable-gpu") driver = webdriver.Chrome(options=options) driver.get(self.kite.login_url()) login_form = WebDriverWait(driver, 45).until( EC.presence_of_element_located((By.CLASS_NAME, "login-form"))) login_form.find_elements_by_tag_name("input")[0].send_keys( self._user_id) login_form.find_elements_by_tag_name("input")[1].send_keys( self._password) WebDriverWait(driver, 45).until( EC.presence_of_element_located((By.CLASS_NAME, "button-orange"))) driver.find_element_by_xpath('//button[@type="submit"]').click() totp_pass = pyotp.TOTP(self._totp).now() twofa_pass = self._pin if self.is_pin is True else totp_pass twofa_form = WebDriverWait(driver, 45).until( EC.presence_of_element_located((By.CLASS_NAME, "twofa-form"))) twofa_form.find_elements_by_tag_name("input")[0].send_keys(twofa_pass) WebDriverWait(driver, 45).until( EC.presence_of_element_located((By.CLASS_NAME, "button-orange"))) driver.find_element_by_xpath('//button[@type="submit"]').click() time.sleep(2) token = get_key(driver.current_url) access = self.kite.generate_session(request_token=token, api_secret=self._secret) self.kite.set_access_token(access["access_token"]) with open("token.tok", "w") as f: f.write(access["access_token"]) driver.close() def get_all_orders_and_positions(self, positions="day"): """ Get the summary of all orders and positions """ pos = pd.DataFrame(self.positions()[positions]) orders = pd.DataFrame(self.orders()) orders["qty"] = orders.eval("pending_quantity-cancelled_quantity") orders["typ"] = "orders" pos["qty"] = pos["quantity"].abs() pos["transaction_type"] = [ "SELL" if qty < 0 else "BUY" for qty in pos.quantity ] pos["typ"] = "positions" cols = ["tradingsymbol", "transaction_type", "qty", "typ"] return pd.concat([pos, orders], sort=False)[cols] def uncovered(self): """ Return the list of uncovered positions A position is considered unconvered if there is no matching stop loss or target order. """ pass def get_order_type(self, price, ltp, order): if order == "BUY": return "LIMIT" if price < ltp else "SL" elif order == "SELL": return "LIMIT" if price > ltp else "SL" @post def orders(self): status_map = { "OPEN": "PENDING", "COMPLETE": "COMPLETE", "CANCELLED": "CANCELED", "CANCELLED AMO": "CANCELED", "REJECTED": "REJECTED", "MODIFY_PENDING": "PENDING", "OPEN_PENDING": "PENDING", "CANCEL_PENDING": "PENDING", "AMO_REQ_RECEIVED": "PENDING", "TRIGGER_PENDING": "PENDING", } ords = self.kite.orders() # Update status for o in ords: o["status"] = status_map.get(o["status"], "PENDING") return ords @post def positions(self): """ Return only the positions for the day """ pos = self.kite.positions()["day"] for p in pos: if p["quantity"] > 0: p["side"] = "BUY" else: p["side"] = "SELL" return pos @pre def order_place(self, **kwargs): """ Place an order """ return self.kite.place_order(**kwargs) def order_cancel(self, order_id, variety="regular", parent_order_id=None): """ Cancel an existing order """ return self.kite.cancel_order(variety=variety, order_id=order_id, parent_order_id=parent_order_id) def order_modify(self, order_id, variety="regular", **kwargs): """ Modify an existing order Note ---- This is just a basic implementation So, all changes must be passed as keyword arguments """ return self.kite.modify_order(order_id=order_id, variety=variety, **kwargs) def _custom_orders(self, data, **kwargs): """ Generate custom orders. This is for customized usage data dataframe with the following columns open, symbol, price, side, quantity and stop_loss kwargs keyword arguments to be included in each order """ cols = ["open", "symbol", "price", "quantity", "side", "stop_loss"] data = data[cols].to_dict(orient="records") exchange = kwargs.get("exchange", "NSE") sym = ["{e}:{s}".format(e=exchange, s=x["symbol"]) for x in data] ltps = self.ltp(sym) ltps = {k[4:]: v["last_price"] for k, v in ltps.items()} all_orders = [] replace = { "symbol": "tradingsymbol", "side": "transaction_type", } for d in data: dct = d.copy() del dct["stop_loss"] ltp = ltps.get(d["symbol"]) order_type = self.get_order_type(price=dct["price"], ltp=ltp, order=dct["side"]) dct["order_type"] = order_type dct["price"] = round(dct["price"], 2) # TO DO: Trigger greater if price is low to correct if order_type == "SL": dct["trigger_price"] = round(dct["open"] - 0.05, 2) dct.update(kwargs) del dct["open"] # Since its no longer needed all_orders.append(self.rename(dct, keys=replace)) # Second leg for covering orders for d in data: try: dct = d.copy() del dct["open"] # Since this is not needed here ltp = ltps.get(dct["symbol"]) dct["side"] = self._sides[dct["side"]] dct["stop_loss"] = round(dct["stop_loss"], 2) order_type = self.get_order_type(price=dct["stop_loss"], ltp=ltp, order=dct["side"]) if order_type == "SL": order_type = "SL-M" dct["order_type"] = order_type dct.update(kwargs) replace.update({"stop_loss": "trigger_price"}) all_orders.append(self.rename(dct, keys=replace)) except Exception as e: print(e, self.rename(dct)) return all_orders def _create_stop(self, **kwargs): sl = self._create_stop_loss_orders(percent=3, **kwargs) orders = [] for s in sl: try: dct = s.copy() dct.update({ "exchange": "NSE", "product": "MIS", "validity": "DAY", "variety": "regular", }) dct["trigger_price"] = s["price"] symbol = "{e}:{sym}".format(e="NSE", sym=s["symbol"]) ltp = self.ltp(symbol)[symbol]["last_price"] order_type = self.get_order_type(s["price"], ltp, s["side"]) dct["order_type"] = order_type orders.append(dct) except Exception as e: print(e) return orders def cover_all(self, **kwargs): """ Place a stop loss for all uncovered orders """ orders = self._create_stop(**kwargs) for o in orders: try: print(self.order_place(**o)) except Exception as e: print(e) def close_all_positions(self, **kwargs): """ Close all existing positions """ positions = self.positions() if kwargs: positions = self.dict_filter(positions, **kwargs) if len(positions) > 0: for position in positions: qty = abs(position["quantity"]) symbol = position["symbol"] side = self._sides[position["side"]] exchange = position["exchange"] product = position["product"] if qty > 0: try: self.order_place( symbol=symbol, quantity=qty, order_type="MARKET", side=side, variety="regular", exchange=exchange, product=product, ) except Exception as e: print(e) def get_instrument_map(self, exchange="NSE", key="tradingsymbol", value="instrument_token"): """ Get the instrument map as a dictionary exchange exchange to fetch the symbols and tokens key dictionary key to be used as the key in the output value dictionary value to be used as the value in the output Note ----- 1) The instrument map is returned as a dictionary with key as the symbol and instrument token as value """ instruments = self.kite.instruments(exchange=exchange) inst_map = {inst[key]: inst[value] for inst in instruments} return inst_map
kite = KiteConnect(api_key="e8aavxmpwesxybqt") # Redirect the user to the login url obtained # from kite.login_url(), and receive the request_token # from the registered redirect url after the login flow. # Once you have the request_token, obtain the access_token # as follows. # reqToken = kite.login_url() # print(reqToken) data = kite.generate_session('o05SEpqqKmSCeome0Hl7PV3OVnvYZMvQ', api_secret="uojmcx5wqk9406nn4ja00ili7mfpiqds") kite.set_access_token(data["access_token"]) print(data) instruments = kite.instruments(exchange='NSE') # instruments.to_csv('instruments.csv') # historyData = kite.historical_data('') # # Place an order # try: # order_id = kite.place_order(tradingsymbol="INFY", # exchange=kite.EXCHANGE_NSE, # transaction_type=kite.TRANSACTION_TYPE_BUY, # quantity=1, # order_type=kite.ORDER_TYPE_MARKET, # product=kite.PRODUCT_NRML) # logging.info("Order placed. ID is: {}".format(order_id)) # except Exception as e: # logging.info("Order placement failed: {}".format(e.message))
target_percent = 0.02 stoploss_percent = 0.05 expiry_year = 2020 expiry_month = 12 # Integer value and add only 1 if the day is 01 expiry_day = 3 # Integer value and add only 1 if the day is 01 nifty_base = 50 banknifty_base = 100 # Initialise api_key = '85j' kite = KiteConnect(api_key=api_key) kite.set_access_token(access_token) kws = KiteTicker(api_key, access_token) # Fetch instruments instruments = kite.instruments(exchange='NFO') df = pd.DataFrame(instruments) df = (df[df['name'] == instrument]) # filter with instrument df = (df[df['expiry'] == datetime.date( year=expiry_year, month=expiry_month, day=expiry_day)] ) # filter with expiry # To return strike value of nifty def nifty_strike(x): return int(nifty_base * round(float(x) / nifty_base)) # To return strike value of banknifty def banknifty_strike(x): return int(banknifty_base * round(float(x) / banknifty_base))
fromDate = datetime(day=datetime.now().day, month=datetime.now().month, year=datetime.now().year, hour=9, minute=15, second=0) toDate = fromDate + timedelta(minutes=29, seconds=59) fromDate = fromDate.strftime('%Y-%m-%d %H:%M:%S') toDate = toDate.strftime('%Y-%m-%d %H:%M:%S') print(fromDate, toDate, TOKENS) for token in TOKENS: data = kite.historical_data(token, fromDate, toDate, '30minute') print(data) DATABASE[token] = pd.DataFrame(data) dataDump = kite.instruments() tokenName = {} for x in TOKENS: for y in dataDump: if (y['instrument_token'] == x): tokenName[x] = y['tradingsymbol'] tokenName for x in DATABASE: DATABASE[x]['buyonce'] = 1 DATABASE[x]['sellonce'] = 1 print(DATABASE[x]) kws = KiteTicker(api_key, access_token_zerodha) BUYEND = datetime.now(pytz.timezone('Asia/Kolkata')).replace(hour=15, minute=30)
class Zerodha(Broker): """ Automated Trading class """ def __init__(self, api_key, secret, user_id, password, PIN, exchange='NSE', product='MIS'): self._api_key = api_key self._secret = secret self._user_id = user_id self._password = password self._pin = PIN self.exchange = exchange self.product = product self._store_access_token = True super(Zerodha, self).__init__() @property def isNilPositions(self): """ return True if there are no open positions else return False """ temp = pd.DataFrame(self.positions()['net']) if temp.quantity.abs().sum() == 0: return True else: return False @property def isNilPositionsDay(self): """ return True if there are no open positions for the day else return False """ temp = pd.DataFrame(self.positions()['day']) if temp.quantity.abs().sum() == 0: return True else: return False @property def isNilOrders(self): """ return True if there are no pending orders else return False """ pending = [ o for o in self.orders() if o.get('status', 'PENDING') == 'PENDING' ] if len(pending) == 0: return True else: return False def cancel_all_orders(self, retries=5): """ Cancel all existing orders """ for o in self.orders(): try: if o['status'] == 'PENDING': self.order_cancel(variety=o['variety'], order_id=o['order_id'], parent_order_id=o['parent_order_id']) except Exception as e: print(e) i = 0 while not (self.isNilOrders): print('Into the loop') i += 1 for o in self.orders(): try: if o['status'] == 'PENDING': self.order_cancel(variety=o['variety'], order_id=o['order_id'], parent_order_id=o['parent_order_id']) except Exception as e: print(e) if i > retries: print('Breaking out of loop without canceling all orders') break def _shortcuts(self): """ Provides shortcuts to kite functions by mapping functions. Instead of calling at.kite.quote, you would directly call at.quote Note ----- 1) Kite functions are initialized only after authentication 1) Not all functions are supported """ self.margins = self.kite.margins self.profile = self.kite.profile self.ltp = self.kite.ltp self.quote = self.kite.quote self.ohlc = self.kite.ohlc self.trades = self.kite.trades self.holdings = self.kite.holdings self._sides = {'BUY': 'SELL', 'SELL': 'BUY'} def authenticate(self): """ Authenticates a kite session if access token is already available Looks up token in token.tok file Useful for reconnecting instead of logging in again """ try: self.kite = KiteConnect(api_key=self._api_key) with open('token.tok') as f: access_token = f.read() self.kite.set_access_token(access_token) self.kite.profile() self.ticker = KiteTicker(api_key=self._api_key, access_token=self.kite.access_token) self._shortcuts() except TokenException: print('Into Exception') self._login() self._shortcuts() self.ticker = KiteTicker(api_key=self._api_key, access_token=self.kite.access_token) except: print('Unknown Exception') self._login() self._shortcuts() self.ticker = KiteTicker(api_key=self._api_key, access_token=self.kite.access_token) def _login(self): import time self.kite = KiteConnect(api_key=self._api_key) options = Options() options.add_argument('--headless') options.add_argument('--disable-gpu') driver = webdriver.Chrome(options=options) driver.get(self.kite.login_url()) login_form = WebDriverWait(driver, 45).until( EC.presence_of_element_located((By.CLASS_NAME, "login-form"))) login_form.find_elements_by_tag_name('input')[0].send_keys( self._user_id) login_form.find_elements_by_tag_name('input')[1].send_keys( self._password) WebDriverWait(driver, 45).until( EC.presence_of_element_located((By.CLASS_NAME, "button-orange"))) driver.find_element_by_xpath('//button[@type="submit"]').click() twofa_form = WebDriverWait(driver, 45).until( EC.presence_of_element_located((By.CLASS_NAME, "twofa-form"))) twofa_form.find_elements_by_tag_name('input')[0].send_keys(self._pin) WebDriverWait(driver, 45).until( EC.presence_of_element_located((By.CLASS_NAME, "button-orange"))) driver.find_element_by_xpath('//button[@type="submit"]').click() time.sleep(2) token = get_key(driver.current_url) access = self.kite.generate_session(request_token=token, api_secret=self._secret) self.kite.set_access_token(access['access_token']) with open("token.tok", "w") as f: f.write(access['access_token']) driver.close() def get_all_orders_and_positions(self, positions='day'): """ Get the summary of all orders and positions """ pos = pd.DataFrame(self.positions()[positions]) orders = pd.DataFrame(self.orders()) orders['qty'] = orders.eval('pending_quantity-cancelled_quantity') orders['typ'] = 'orders' pos['qty'] = pos['quantity'].abs() pos['transaction_type'] = [ 'SELL' if qty < 0 else 'BUY' for qty in pos.quantity ] pos['typ'] = 'positions' cols = ['tradingsymbol', 'transaction_type', 'qty', 'typ'] return pd.concat([pos, orders], sort=False)[cols] def uncovered(self): """ Return the list of uncovered positions A position is considered unconvered if there is no matching stop loss or target order. """ pass def get_order_type(self, price, ltp, order): if order == "BUY": return 'LIMIT' if price < ltp else 'SL' elif order == "SELL": return 'LIMIT' if price > ltp else 'SL' @post def orders(self): status_map = { 'OPEN': 'PENDING', 'COMPLETE': 'COMPLETE', 'CANCELLED': 'CANCELED', 'CANCELLED AMO': 'CANCELED', 'REJECTED': 'REJECTED', 'MODIFY_PENDING': 'PENDING', 'OPEN_PENDING': 'PENDING', 'CANCEL_PENDING': 'PENDING', 'AMO_REQ_RECEIVED': 'PENDING', 'TRIGGER_PENDING': 'PENDING' } ords = self.kite.orders() # Update status for o in ords: o['status'] = status_map.get(o['status'], 'PENDING') return ords @post def positions(self): """ Return only the positions for the day """ pos = self.kite.positions()['day'] for p in pos: if p['quantity'] > 0: p['side'] = 'BUY' else: p['side'] = 'SELL' return pos @pre def order_place(self, **kwargs): """ Place an order """ return self.kite.place_order(**kwargs) def order_cancel(self, order_id, variety='regular', parent_order_id=None): """ Cancel an existing order """ return self.kite.cancel_order(variety=variety, order_id=order_id, parent_order_id=parent_order_id) def order_modify(self, order_id, variety='regular', **kwargs): """ Modify an existing order Note ---- This is just a basic implementation So, all changes must be passed as keyword arguments """ return self.kite.modify_order(order_id=order_id, variety=variety, **kwargs) def _custom_orders(self, data, **kwargs): """ Generate custom orders. This is for customized usage data dataframe with the following columns open, symbol, price, side, quantity and stop_loss kwargs keyword arguments to be included in each order """ cols = ['open', 'symbol', 'price', 'quantity', 'side', 'stop_loss'] data = data[cols].to_dict(orient='records') exchange = kwargs.get('exchange', 'NSE') sym = ['{e}:{s}'.format(e=exchange, s=x['symbol']) for x in data] print(sym) ltps = self.ltp(sym) ltps = {k[4:]: v['last_price'] for k, v in ltps.items()} print(ltps) all_orders = [] replace = { 'symbol': 'tradingsymbol', 'side': 'transaction_type', } for d in data: dct = d.copy() del dct['stop_loss'] ltp = ltps.get(d['symbol']) order_type = self.get_order_type(price=dct['price'], ltp=ltp, order=dct['side']) dct['order_type'] = order_type dct['price'] = round(dct['price'], 2) # TO DO: Trigger greater if price is low to correct if order_type == "SL": dct['trigger_price'] = round(dct['open'] - 0.05, 2) dct.update(kwargs) del dct['open'] # Since its no longer needed all_orders.append(self.rename(dct, keys=replace)) # Second leg for covering orders for d in data: try: dct = d.copy() del dct['open'] # Since this is not needed here ltp = ltps.get(dct['symbol']) dct['side'] = self._sides[dct['side']] dct['stop_loss'] = round(dct['stop_loss'], 2) order_type = self.get_order_type(price=dct['stop_loss'], ltp=ltp, order=dct['side']) if order_type == 'SL': order_type = 'SL-M' dct['order_type'] = order_type dct.update(kwargs) replace.update({'stop_loss': 'trigger_price'}) all_orders.append(self.rename(dct, keys=replace)) except Exception as e: print(e, self.rename(dct)) return all_orders def _create_stop(self, **kwargs): sl = self._create_stop_loss_orders(percent=3, **kwargs) orders = [] for s in sl: try: dct = s.copy() dct.update({ 'exchange': 'NSE', 'product': 'MIS', 'validity': 'DAY', 'variety': 'regular' }) dct['trigger_price'] = s['price'] symbol = '{e}:{sym}'.format(e='NSE', sym=s['symbol']) ltp = self.ltp(symbol)[symbol]['last_price'] order_type = self.get_order_type(s['price'], ltp, s['side']) dct['order_type'] = order_type orders.append(dct) except Exception as e: print(e) return orders def cover_all(self, **kwargs): """ Place a stop loss for all uncovered orders """ orders = self._create_stop(**kwargs) for o in orders: try: print(self.order_place(**o)) except Exception as e: print(e) def close_all_positions(self, **kwargs): """ Close all existing positions """ positions = self.positions() if kwargs: positions = self.dict_filter(positions, **kwargs) if len(positions) > 0: for position in positions: qty = abs(position['quantity']) symbol = position['symbol'] side = self._sides[position['side']] exchange = position['exchange'] product = position['product'] if qty > 0: try: self.order_place(symbol=symbol, quantity=qty, order_type='MARKET', side=side, variety='regular', exchange=exchange, product=product) except Exception as e: print(e) def get_instrument_map(self, exchange='NSE', key='tradingsymbol', value='instrument_token'): """ Get the instrument map as a dictionary exchange exchange to fetch the symbols and tokens key dictionary key to be used as the key in the output value dictionary value to be used as the value in the output Note ----- 1) The instrument map is returned as a dictionary with key as the symbol and instrument token as value """ instruments = self.kite.instruments(exchange=exchange) inst_map = {inst[key]: inst[value] for inst in instruments} return inst_map
class kiteparse: def __init__(self): self.kite = KiteConnect(api_key="2x2f2a8447agu452") print(self.kite.login_url()) access_token = input("Enter token:") data = self.kite.generate_session( access_token, api_secret="kfygfd0sgae19vnmsz49pnd1t44dacb1") self.kite.set_access_token(data["access_token"]) data = self.kite.instruments() df = pd.DataFrame(data)[[ "instrument_token", "exchange_token", "tradingsymbol", "exchange" ]] df.to_csv("instruments_com.csv") def read_data_backtest(self, symbol_1, interval, exchange="NSE", symbol=True, minute=0): instrument = symbol_1 if symbol: list_x = pd.read_csv("instruments_com.csv") dat = list_x.loc[list_x['tradingsymbol'] == symbol_1, ['exchange', 'instrument_token']] instrument = dat.loc[dat['exchange'] == exchange, 'instrument_token'].iloc[0] from datetime import time tzinfo = pytz.timezone('Asia/Kolkata') now = datetime.now(tz=tzinfo) #tz= tzinf today = now.date() current_time = time(now.hour, now.minute, now.second) # print(current_time,today, today.weekday()) if current_time < time(9, 15, 00) and today.weekday() == 0: current_time = time(9, 15, 00) to_d = datetime.combine(today - timedelta(days=3), current_time) + timedelta(minutes=minute) elif current_time < time(9, 15, 00) and today.weekday() in range(5): current_time = time(9, 15, 00) to_d = datetime.combine(today - timedelta(days=1), current_time) + timedelta(minutes=minute) elif current_time > time(15, 31, 00) and today.weekday() in range(5): current_time = time(9, 15, 00) to_d = datetime.combine(today, current_time) + timedelta(minutes=minute) elif today.weekday() == 5: current_time = time(9, 15, 00) to_d = datetime.combine(today - timedelta(days=1), current_time) + timedelta(minutes=minute) elif today.weekday() == 6: current_time = time(9, 15, 00) to_d = datetime.combine(today - timedelta(days=2), current_time) + timedelta(minutes=minute) elif today.weekday() in range(5): to_d = datetime.combine(today, current_time) if interval == "2minute": period = timedelta(minutes=400 * 2 + 3550) from_d = to_d - period if interval == "5minute": period = timedelta(minutes=400 * 5 + 5550) from_d = to_d - period if interval == "10minute": period = timedelta(minutes=400 * 10 + 12550) from_d = to_d - period if interval == "15minute": period = timedelta(minutes=400 * 15 + 18550) from_d = to_d - period if interval == "30minute": period = timedelta(minutes=400 * 30 + 40550) from_d = to_d - period if interval == "60minute": period = timedelta(hours=2500) from_d = to_d - period if interval == "2hour": period = timedelta(hours=5000) from_d = to_d - period if interval == "3hour": period = timedelta(hours=8000) from_d = to_d - period if interval == "day": period = timedelta(days=399) from_d = to_d - period #from_d = datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) ohlcv = pd.DataFrame( self.kite.historical_data(instrument_token=instrument, from_date=from_d, to_date=to_d, interval=interval)) return ohlcv, to_d def placeorder(self, item, exchange, action, quantity): try: order_id = kite.place_order(tradingsymbol=item, exchange=exchange, transaction_type=action, quantity=quantity, variety="regular", order_type="MARKET", product="MIS") logging.info("Order placed. ID is: {}".format(order_id)) except Exception as e: print(e)
def fetch_all_instruments(access_token): kite = KiteConnect(access_token=access_token, api_key="wr4m14tgk52gn65y") instruments = kite.instruments() df = pd.DataFrame(instruments) return df
tick_data = [] start_date = pd.to_datetime('01/01/2015', dayfirst=True, format='%d/%m/%Y') while start_date < pd.datetime.now(): end_date = start_date + pd.Timedelta( days=historical_data_limits[interval]) data = kite.historical_data(self.kite_id, start_date, end_date, interval) tick_data.extend(data) start_date = end_date + pd.Timedelta(days=1) if tick_data: return (tick_data) else: pass instruments = pd.DataFrame(kite.instruments()) instruments = instruments[(instruments['lot_size'] == 1) & (instruments['expiry'] == '') & (instruments['segment'] == 'NSE')] instruments = instruments.sort_values(by='tradingsymbol', axis=0) instruments = instruments.reset_index(drop=True) for i in range(760, 1140): download_class = HistoricalData(instruments.iloc[i, 0]) data = pd.DataFrame(download_class.get_max_data()) # Enter Path Here data.to_csv('your_path_here/{}.csv'.format(instruments.iloc[i, 2])) print('-----Done {} : {}-----'.format(i - 759, instruments.iloc[i, 2]))
from kiteconnect import KiteConnect import pandas as pd import datetime as dt import os import numpy as np cwd = os.chdir("D:\\Udemy\\Zerodha KiteConnect API\\1_account_authorization") #generate trading session access_token = open("access_token.txt", 'r').read() key_secret = open("api_key.txt", 'r').read().split() kite = KiteConnect(api_key=key_secret[0]) kite.set_access_token(access_token) #get dump of all NSE instruments instrument_dump = kite.instruments("NSE") instrument_df = pd.DataFrame(instrument_dump) def instrumentLookup(instrument_df, symbol): """Looks up instrument token for a given script from instrument dump""" try: return instrument_df[instrument_df.tradingsymbol == symbol].instrument_token.values[0] except: return -1 def fetchOHLC(ticker, interval, duration): """extracts historical data and outputs in the form of dataframe""" instrument = instrumentLookup(instrument_df, ticker)
r = requests.get(url) text = r.iter_lines() reader = csv.reader(text, delimiter=',') firstline = True nifty500 = [] for lines in reader: if firstline: #skip first line firstline = False continue nifty500.append(lines[2]) print lines[2] kite = KiteConnect(api_key="yw8yelu5bpfel8ib") kite.set_access_token("s4on3tuaxkiquqxws5duxx0n3xgszdmi") instruments = kite.instruments("NSE") nifty500dict = {} for symbol in nifty500: for k in instruments: if k["tradingsymbol"] == symbol: nifty500dict[k["exchange_token"]] = k["tradingsymbol"] print nifty500dict print(len(nifty500dict)) conn = sqlite3.connect(r"instruments.db") c = conn.cursor() for k in nifty500dict.keys():