class DataBank: def __init__(self, access_token, api_key, from_date, to_date): self.kite = KiteConnect(api_key=api_key) self.kite.set_access_token(access_token=access_token) all_tradables = pd.read_csv('full_list.csv') self.dict_all_tradables = all_tradables.to_dict(orient='records') self.from_date, self.to_date = from_date, to_date print(self.dict_all_tradables) self.data = {} mean_values = [] update_tradables = [] for x in self.dict_all_tradables: print(x) while True: try: time.sleep(0.5) hist_data = pd.DataFrame( self.kite.historical_data(x['instrument_token'], from_date=self.from_date, to_date=self.to_date, interval='day')) x['mean_volume'] = statistics.mean( hist_data['volume'].tolist()) x['mean_price'] = statistics.mean( hist_data['close'].tolist()) x['mean_value'] = x['mean_price'] * x['mean_volume'] mean_values.append(x['mean_value']) update_tradables.append(x) except Exception as e: print(e) continue break average_mean_value = sum(mean_values) / len(mean_values) updated = [] for y in update_tradables: 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')
def fetch_data(access_token, instrument, start_date, end_date, interval): if (interval not in polling_intervals.keys()): print("Invalid Interval") return null max_days = polling_intervals[interval] historical_data = [] kite = KiteConnect(access_token=access_token, api_key="wr4m14tgk52gn65y") while (start_date < end_date): historical_data.extend( kite.historical_data( instrument, start_date, min(start_date + dt.timedelta(days=max_days), end_date), interval)) start_date += dt.timedelta(days=max_days) df = pd.DataFrame(historical_data) return df
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)
shortpos_count=0 dir_path2=os.path.dirname(os.path.realpath(__file__)) api_key=open(dir_path2 +"\\Access Details\\" +"api_key.txt","r").read() access_token=open(dir_path2 +"\\Access Details\\" +"access_token.txt","r").read() kite=KiteConnect(api_key=api_key) kite.set_access_token(access_token) while True: now = datetime.now() current_time = str(now.strftime("%H-%M-%S")) data_Extract_raw1 = pd.DataFrame(kite.historical_data(738561,dt.date.today()-dt.timedelta(200), dt.datetime.now(),"day")) data_Extract1= data_Extract_raw1.set_index('date') #data_Extract1.to_csv("bla.csv") priceBand1=[data_Extract1['close'][-counterprice] for counterprice in range(100,0,-1) ] ATR=[(sum([max(data_Extract1['high'][-count] - data_Extract1['low'][-count], \ abs(data_Extract1['high'][-count] - data_Extract1['close'][-(count+1)]), \ abs(data_Extract1['low'][-count] - data_Extract1['close'][-(count+1)])) \ for count in range(counterprime,counterprime-7,-1)])/7) \ for counterprime in range(100,6,-1)]
interval = "1minute" token_data = json.load(open("token.json")) token_symbol = token_data["symbol"] quantity = token_data["quantity"] ticker = token_data["ticker"] isLong, isShort = False, False current_position_details = {} while True: if datetime.now().seconds == 0: token_data = kite.historical_data(ticker, from_date=from_date, to_date=to_date, interval=interval) df_token_data = pd.Dataframe(token_data) df_token_data.drop(df_token_data.tail(1).index, inplace=True) token_sma_5 = sma(df_token_data, 5) token_sma_15 = sma(df_token_data, 15) if token_sma_5.iloc(-2) <= token_sma_15.iloc( -2) and token_sma_5.iloc(-1) > token_sma_15.iloc(-1): if isShort: try: order_id = kite.place_order( variety=kite.VARIETY_REGULAR, tradingsymbol=token_symbol, exchange=kite.EXCHANGE_NSE,
access_token=open(dir_path +"\\Access Details\\" +"access_token.txt","r").read() kite=KiteConnect(api_key=api_key) kite.set_access_token(access_token) ###################### ###################### ###################### ###################### for token in token_list: try: data_Extract = pd.DataFrame(kite.historical_data(token,dt.date.today()-dt.timedelta(50), dt.datetime.now(),"day")) data_Extract1= data_Extract.set_index('date') Price_Data=data_Extract1['close'] timestamp1=data_Extract1.index[-1] Price_Data_ext=Price_Data price_list1=[ i1 for i1 in Price_Data_ext[-34:]] price_change1= [price_list1[count1]-price_list1[count1-1] for count1 in range(1,len(price_list1))] postiveChange1=[ priceChange_per1 if priceChange_per1>0 else 0 for priceChange_per1 in price_change1] negativeChange1=[abs(priceChange_per1) if priceChange_per1<0 else 0 for priceChange_per1 in price_change1] avg_pos_gain=[] avg_pos_gain.append(sum(postiveChange1[0:14])/len(postiveChange1[0:14])) for gain_i in postiveChange1[-19:]: avg_gain1= ((avg_pos_gain[-1] * 13) + gain_i )/14
long_pos = 0 short_pos = 0 dir_path = os.path.normpath(os.getcwd() + os.sep + os.pardir) dir_path2 = os.path.dirname(os.path.realpath(__file__)) api_key = open(dir_path2 + "\\Access Details\\" + "api_key.txt", "r").read() access_token = open(dir_path2 + "\\Access Details\\" + "access_token.txt", "r").read() kite = KiteConnect(api_key=api_key) kite.set_access_token(access_token) data_Extract = pd.DataFrame( kite.historical_data(5633, dt.date.today() - dt.timedelta(3), dt.datetime.now(), "minute")) # data_Extract1= data_Extract.set_index('date') Current_MA5 = sum(data_Extract['close'][-6:-1]) / 5 Current_MA50 = sum(data_Extract['close'][-51:-1]) / 50 if long_pos == 0 and short_pos == 0: if Current_MA5 > Current_MA50: bookbuy_order(tk_name) print( str(tk_name) + " | " + "Open Long Position" + " | " + "Current price- " + str(data_Extract1['close'][-1])) long_pos = 1 if Current_MA5 < Current_MA50: booksell_order(tk_name)
kite.set_access_token(access_token) # Calculate Gap UP/Down For Stocks in list stock_list = pd.read_csv(info_file_path) # Initializing Counter for Selected Stock Dataset selected_stock_initialize_flag = 0 # Iterate over all the available scrips stock_list = info_data for i in stock_list.index.values: # Get Previous Weekday and today's day level candle data day_compare_data = kite.historical_data( instrument_token=stock_list['Token'][i], from_date=date_from, to_date=today, interval=interval) day_compare_data = pd.DataFrame(day_compare_data) print(stock_list['Company'][i]) day_compare_data.columns = [ 'Close', 'Date', 'High', 'Low', 'Open', 'Volume' ] # Convert date column into date format day_compare_data['Date'] = [str(i) for i in day_compare_data['Date']] day_compare_data['Date'] = [ i[:i.find('+')] for i in day_compare_data['Date'] ] day_compare_data['Date'] = [ datetime.strptime(i, '%Y-%m-%d %H:%M:%S')
import statistics access_token = 'wRN7tG9IKSLFhmveBm59R8gmFML8oKwh' api_key = '7lwrah449p8wk3i0' kite = KiteConnect(api_key=api_key) kite.set_access_token(access_token=access_token) df_comp = pd.read_json('full_list.json') dict_list_comp = df_comp.to_dict(orient='records') dict_comp_wr = {} for i in dict_list_comp: oversold_sum = 0 undersold_sum = 0 df_data = pd.DataFrame( kite.historical_data(instrument_token=i['instrument_token'], from_date='2018-08-30', to_date='2018-09-10', interval='5minute')) df_data['wr'] = ta.WILLR(df_data['high'], df_data['low'], df_data['close'], timeperiod=40) np_data = df_data['wr'].tolist() i['mean_price'] = statistics.mean(df_data['close'].tolist()) for j in np_data: if j > -20: oversold_sum = oversold_sum + abs(j + 20) elif j < -80: undersold_sum = undersold_sum + abs(j + 80) dict_comp_wr[i['symbol']] = oversold_sum / undersold_sum new_tradables = []
tickers_to_insid["WIPRO"] = "129967364" tickers_to_insid["TATAMOTORS"] = "128145924" tickers_to_insid["IOC"] = "135927044" tickers_to_insid["INFRATEL"] = "136912900" tickers_to_insid["ITC"] = "128224004" tickers_to_insid["ZEEL"] = "129417476" tickers_to_insid["ONGC"] = "128079876" tickers_to_insid["NTPC"] = "136334084" ohlc_intraday = {} start = dt.datetime.today() - dt.timedelta(100) end = dt.datetime.today() for ticker in tickers: ohlc_intraday[ticker] = kite.historical_data(tickers_to_insid[ticker], start, end, "5minute") # ohlc_intraday = pickle.load(open( "ohlc_intraday.pickle", "rb" )) # for ticker in tickers: # ohlc_intraday[ticker] = pd.DataFrame(ohlc_intraday[ticker]) # ohlc_renko = {} # df = copy.deepcopy(ohlc_intraday) # tickers_signal = {} # tickers_ret = {} # for ticker in tickers: # print("merging for ",ticker) # renko = renko_DF(df[ticker]) # renko.columns = ["date","open","high","low","close","uptrend","bar_num"] # renko["date"] = pd.to_datetime(renko["date"], format='%Y-%m-%d %H:%M:%S%z')
def start(name, token, access_token, timeframe): # print("Starting Trading Engine...", flush=True) config = configparser.ConfigParser() # path = os.getcwd() path = '/home/ubuntu/APT/APT/Paper_Trading' config_path = path + '/config.ini' config.read(config_path) api_key = config['API']['API_KEY'] kite = KiteConnect(api_key=api_key) kite.set_access_token(access_token) # Get previous day candle def prev_weekday(adate): holiday_list=['2019-10-02','2019-10-08','2019-10-08','2019-11-12','2019-12-25'] adate -= timedelta(days=1) if adate.strftime('%Y-%m-%d') in holiday_list: adate -= timedelta(days=1) while adate.weekday() > 4: adate -= timedelta(days=1) return adate date_from = prev_weekday(date.today()) date_to = date_from interval = 'day' previous_day_data = kite.historical_data(instrument_token=token[0], from_date=date_from, to_date=date_to, interval=interval) previous_day_data = pd.DataFrame(previous_day_data) previous_day_data.columns = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume'] previous_day_data.to_csv("previous_day_data_"+ name +'.csv') # Sleep till 9:15 time_now = datetime.now() sleep_time = 60 - time_now.second time.sleep(sleep_time) time_now = datetime.now() print('Script Started at ' + str(time_now),flush=True) # Initialise print("Initialising Kite Ticker") kws = KiteTicker(api_key, access_token) start.tick_df = pd.DataFrame(columns=['Token', 'Timestamp', 'LTP'], index=pd.to_datetime([])) start.last_saved_time = 10 def on_ticks(ws, ticks): # Callback to receive ticks. # print(ticks) # print(ticks[0]['timestamp'] >= datetime.now().replace(hour= 9,minute= 15, second = 0,microsecond = 0)) # print(ticks[0]['timestamp'] >= datetime.strptime('1970-01-01 00:00:00','%Y-%m-%d %H:%M:%S')) if ticks[0]['timestamp'] >= datetime.now().replace(hour= 3,minute= 45, second = 0,microsecond = 0): # if ticks[0]['timestamp'] >= datetime.strptime('1970-01-01 00:00:00','%Y-%m-%d %H:%M:%S'): print(ticks) start.tick_df = start.tick_df.append({'Token': ticks[0]['instrument_token'], 'Timestamp': ticks[0]['timestamp'], 'LTP': ticks[0]['last_price']}, ignore_index=True) if (start.tick_df['Timestamp'][len(start.tick_df) - 1].minute % 5 == 0) and (start.tick_df['Timestamp'][len(start.tick_df) - 1].minute != start.last_saved_time): # save the last minute start.last_saved_time = start.tick_df['Timestamp'][len(start.tick_df) - 1].minute # drop last row start.tick_df.drop(start.tick_df.tail(1).index, inplace=True) print(len(start.tick_df)) # set timestamp as index start.tick_df = start.tick_df.set_index(['Timestamp']) start.tick_df['Timestamp'] = pd.to_datetime(start.tick_df.index, unit='s') # convert to OHLC format data_ohlc = start.tick_df['LTP'].resample(timeframe).ohlc() print(data_ohlc) # save the dataframe to csv data_ohlc.to_csv('ohlc_data_' + name +'.csv') print("Printed at " + str(datetime.now())) # initialize the dataframe start.tick_df = pd.DataFrame(columns=['Token', 'Timestamp', 'LTP'], index=pd.to_datetime([])) print(len(data_ohlc)) def on_connect(ws, response): # Callback on successful connect. # Subscribe to a list of instrument_tokens ws.subscribe(token) # Set TITAN to tick in `full` mode. ws.set_mode(ws.MODE_FULL, token) # Callback when current connection is closed. def on_close(ws, code, reason): logging.info("Connection closed: {code} - {reason}".format(code=code, reason=reason)) # Callback when connection closed with error. def on_error(ws, code, reason): logging.info("Connection error: {code} - {reason}".format(code=code, reason=reason)) # Callback when reconnect is on progress def on_reconnect(ws, attempts_count): logging.info("Reconnecting: {}".format(attempts_count)) # Callback when all reconnect failed (exhausted max retries) def on_noreconnect(ws): logging.info("Reconnect failed.") # Assign the callbacks. kws.on_ticks = on_ticks kws.on_close = on_close kws.on_error = on_error kws.on_connect = on_connect kws.on_reconnect = on_reconnect kws.on_noreconnect = on_noreconnect print("Callbacks assigned") # Infinite loop on the main thread. Nothing after this will run. # You have to use the pre-defined callbacks to manage subscriptions. kws.connect() print("KWS disconnected")
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)
wb = xw.Book('config.xlsx') def read_excel(): sht = wb.sheets['Sheet1'] for x in range(1, 1000): val = sht.range('A' + str(x)).value if val == None: break name = val.split("/")[0] token = int(val.split("/")[1]) trd_portfolio[name] = {"token": token} read_excel() sht2 = wb.sheets['Sheet2'] from_date = sht2.range('A1').value to_date = sht2.range('A2').value interval = sht2.range('A3').value # pdb.set_trace() print(f"dates are {from_date}----> {to_date} for {interval}") for name in trd_portfolio: token = trd_portfolio[name]['token'] records = kite.historical_data(token, from_date, to_date, interval) df = pd.DataFrame(records) df.to_csv(name + ".csv") print(f"got data for {name}")
testEnd = baseTest.replace(hour=15, minute=29, second=59) testStart = testStart.strftime('%Y-%m-%d %H:%M:%S') testEnd = testEnd.strftime('%Y-%m-%d %H:%M:%S') todayCandle = datetime.now() todayCandleStart = todayCandle.replace(hour=9, minute=15, second=0) todayCandleEnd = todayCandle.replace(hour=9, minute=29, second=59) todayCandleStart = todayCandleStart.strftime('%Y-%m-%d %H:%M:%S') todayCandleEnd = todayCandleEnd.strftime('%Y-%m-%d %H:%M:%S') for token in allTokens: yesterdayData = 1 #print(token) while yesterdayData: try: data = kite.historical_data(token, testStart, testEnd, '15minute') except: break if (data): yesterdayData = 0 else: baseTest = baseTest - timedelta(days=1) testStart = baseTest.replace(hour=14, minute=15, second=0) testEnd = baseTest.replace(hour=15, minute=29, second=59) testStart = testStart.strftime('%Y-%m-%d %H:%M:%S') testEnd = testEnd.strftime('%Y-%m-%d %H:%M:%S') #print(kite.historical_data(token,todayCandleStart,todayCandleEnd,'15minute')) todayVolume = kite.historical_data(token, todayCandleStart, todayCandleEnd, '15minute')[0]['volume'] movingAvg = [x['volume'] for x in data] movingAvg = movingAverage(movingAvg) * 1.5
for name, token in scrip_dict.items(): flag = 0 in_path = path + "/" + item[2] + "/" + name if not os.path.exists(in_path): os.mkdir(in_path) print("Directory", in_path, "Created ") else: print("Directory", in_path, "already exists") for interval in interval_list: if flag == 1: interval = 'minute' if not os.path.exists(in_path + "/" + interval + 'data.csv'): try: print("in try block") data = kite.historical_data(instrument_token=token, from_date=item[0], to_date=item[1], interval=interval) flag = 0 except: print("in except block") flag = 1 continue else: print(name + " " + interval + " already exists") continue data = pd.DataFrame(data) print(name + "-" + interval) data.to_csv(in_path + "\\" + interval + '.csv') print("Data for " + name + " for interval " + interval + " is saved")
class Marination: def __init__(self, from_date, to_date, access_token, api_key): self.kite = KiteConnect(api_key=api_key) self.kite.set_access_token(access_token=access_token) self.from_date = from_date self.to_date = to_date self.api_key = api_key self.access_token = access_token self.holder_of_subscription_classes = {} self.holder_of_subscription_classes_entry = {} self.df_tradables = pd.read_csv('tradables.csv') self.dict_trabables = self.df_tradables.to_dict(orient='records') for x in self.dict_trabables: x['class'] = pe.PreEntry(x, api_key=self.api_key, access_token=self.access_token) self.holder_of_subscription_classes_entry[ x['instrument_token']] = x['class'] self.positions = self.dict_trabables self.position_reader() def ticks_handler(self, ticks): threads = [] for tick in ticks: thread = threading.Thread(target=self.thread_ticks(tick)) threads.append(thread) thread.start() for t in threads: t.join() def position_reader(self): threads = [] for x in self.positions: thread = threading.Thread(target=self.thread_positions(x)) threads.append(thread) thread.start() for t in threads: t.join() def thread_ticks(self, tick): self.holder_of_subscription_classes[tick[ 'instrument_token']].long = self.holder_of_subscription_classes_entry[ tick['instrument_token']].long_position self.holder_of_subscription_classes[tick[ 'instrument_token']].short = self.holder_of_subscription_classes_entry[ tick['instrument_token']].short_position self.holder_of_subscription_classes_entry[tick['instrument_token']].buy_price = \ self.holder_of_subscription_classes_entry[tick['instrument_token']].buy_price self.holder_of_subscription_classes_entry[tick['instrument_token']].sell_price = \ self.holder_of_subscription_classes_entry[tick['instrument_token']].sell_price self.holder_of_subscription_classes_entry[tick['instrument_token']].long_position, \ self.holder_of_subscription_classes_entry[tick['instrument_token']].short_position = \ self.holder_of_subscription_classes[tick['instrument_token']].tick_handler(tick) self.holder_of_subscription_classes_entry[ tick['instrument_token']].entry( self.holder_of_subscription_classes[ tick['instrument_token']].hist_data, self.holder_of_subscription_classes[ tick['instrument_token']].std_dev_holder.np_emas, tick) def thread_positions(self, x): df_data = pd.DataFrame( self.kite.historical_data(instrument_token=x['instrument_token'], from_date=self.from_date, to_date=self.to_date, interval='5minute')) df_data = df_data.set_index(pd.to_datetime(df_data['date'])) df_data = df_data.drop('date', axis=1) df_data = df_data.drop('volume', axis=1) df_data = df_data.sort_index() x['data'] = df_data x['class'] = sc.Stock(x, 5000, api_key=self.api_key, access_token=self.access_token) self.holder_of_subscription_classes[x['instrument_token']] = x['class'] self.holder_of_subscription_classes[x['instrument_token']].quantity = 3
class KiteOrderManager(): __instance = None @staticmethod def GetInstance(): ''' Static access method''' if KiteOrderManager.__instance == None: KiteOrderManager() return KiteOrderManager.__instance def __init__(self): if KiteOrderManager.__instance != None: raise Exception("KiteOrderManager!This class is singleton!") else: KiteOrderManager.__instance = self print "Kite order manager statring..." self.InitialiseKite() print "Kite order manager complete..." def InitialiseKite(self): logging.info("Kite order manager statring...") tokenManager = TokenManager.GetInstance() apiKey = tokenManager.GetApiKey() accessToken = tokenManager.GetAccessToken() self.kite = KiteConnect(api_key=apiKey) self.kite.set_access_token(accessToken) logging.info("Kite order manager complete...") def BuyOrder(self): print "Not implemented" def SellOrder(self): print "Not implemented" def BuyOrder(self, symbol, tradePrice, targetPoint, stoplossPoint, trailingSL, quantity): if ORDER_TYPE == 'BO': return self.BuyBracketOrder(symbol, tradePrice, targetPoint, stoplossPoint, trailingSL, quantity) elif ORDER_TYPE == 'MIS': return self.BuyMISOrder(symbol, tradePrice, targetPoint, stoplossPoint, quantity) def SellOrder(self, symbol, tradePrice, targetPoint, stoplossPoint, trailingSL, quantity): if ORDER_TYPE == 'BO': return self.SellBracketOrder(symbol, tradePrice, targetPoint, stoplossPoint, trailingSL, quantity) elif ORDER_TYPE == 'MIS': return self.SellMISOrder(symbol, tradePrice, targetPoint, stoplossPoint, quantity) def BuyBracketOrder(self, symbol, tradePrice, targetPoint, stoplossPoint, trailingSL, quantity): #print "Order for symol: "+ symbol + " for quantity " + str(quantity) + " placed at price " + str(tradePrice) + " targetpoint " + str(targetPoint) + " stoplosspoint " + str(stoplossPoint) #quantity = 1 try: orderNo = self.kite.place_order( variety=self.kite.VARIETY_BO, exchange=self.kite.EXCHANGE_NSE, #NFO or NSE tradingsymbol=symbol, transaction_type=self.kite.TRANSACTION_TYPE_BUY, quantity=quantity, product=self.kite.PRODUCT_BO, order_type=self.kite.ORDER_TYPE_LIMIT, price=tradePrice, validity=None, disclosed_quantity=None, trigger_price=None, squareoff=targetPoint, stoploss=stoplossPoint, trailing_stoploss=None, tag=None) if orderNo != "": print "Order for symol: " + symbol + " for quantity " + str( quantity) + " placed at price " + str( tradePrice) + " .Order no is:" + str(orderNo) logging.info("Order for symol: " + symbol + " for quantity " + str(quantity) + " placed at price " + str(tradePrice) + " .Order no is:" + str(orderNo)) return orderNo except kiteexceptions.TokenException as e: self.DumpExceptionInfo(e, "BuyBracketOrder") logging.info("Initialising kite again...") print "Initialising kite again..." self.InitialiseKite() return "" def BuyMISOrder(self, symbol, tradePrice, targetPoint, stoplossPoint, quantity): try: orderNo = self.kite.place_order( variety=self.kite.VARIETY_REGULAR, exchange=self.kite.EXCHANGE_NSE, tradingsymbol=symbol, transaction_type=self.kite.TRANSACTION_TYPE_BUY, quantity=quantity, product=self.kite.PRODUCT_MIS, order_type=self.kite.ORDER_TYPE_MARKET, #price=tradePrice, validity=None, disclosed_quantity=None, trigger_price=None, #squareoff=targetPoint, #stoploss=stoplossPoint, trailing_stoploss=None, tag=None) print "Order for symol: " + symbol + " for quantity " + str( quantity) + " placed at price " + str( tradePrice) + " .Order no is:" + str(orderNo) logging.info("Order for symol: " + symbol + " for quantity " + str(quantity) + " placed at price " + str(tradePrice) + " .Order no is:" + str(orderNo)) return orderNo except kiteexceptions.TokenException as e: self.DumpExceptionInfo(e, "BuyMISOrder") logging.info("Initialising kite again...") print "Initialising kite again..." self.InitialiseKite() return "" def SellBracketOrder(self, symbol, tradePrice, targetPoint, stoplossPoint, trailingSL, quantity): #print "Order for symol: "+ symbol + " for quantity " + str(quantity) + " placed at price " + str(tradePrice) + " targetpoint " + str(targetPoint) + " stoplosspoint " + str(stoplossPoint) #quantity = 1 try: orderNo = self.kite.place_order( variety=self.kite.VARIETY_BO, exchange=self.kite.EXCHANGE_NSE, # NFO or NSE tradingsymbol=symbol, transaction_type=self.kite.TRANSACTION_TYPE_SELL, quantity=quantity, product=self.kite.PRODUCT_BO, order_type=self.kite.ORDER_TYPE_LIMIT, price=tradePrice, validity=None, disclosed_quantity=None, trigger_price=None, squareoff=targetPoint, stoploss=stoplossPoint, trailing_stoploss=None, tag=None) if orderNo != "": print "Order for symol: " + symbol + " for quantity " + str( quantity) + " placed at price " + str( tradePrice) + " .Order no is:" + str(orderNo) logging.info("Order for symol: " + symbol + " for quantity " + str(quantity) + " placed at price " + str(tradePrice) + " .Order no is:" + str(orderNo)) return orderNo except kiteexceptions.TokenException as e: self.DumpExceptionInfo(e, "SellBracketOrder") logging.info("Initialising kite again...") print "Initialising kite again..." self.InitialiseKite() return "" def SellMISOrder(self, symbol, tradePrice, targetPoint, stoplossPoint, quantity): try: orderNo = self.kite.place_order( variety=self.kite.VARIETY_REGULAR, exchange=self.kite.EXCHANGE_NSE, tradingsymbol=symbol, transaction_type=self.kite.TRANSACTION_TYPE_SELL, quantity=quantity, product=self.kite.PRODUCT_MIS, order_type=self.kite.ORDER_TYPE_MARKET, #price=tradePrice, validity=None, disclosed_quantity=None, trigger_price=None, #squareoff=targetPoint, #stoploss=stoplossPoint, trailing_stoploss=None, tag=None) print "Order for symol: " + symbol + " for quantity " + str( quantity) + " placed at price " + str( tradePrice) + " .Order no is:" + str(orderNo) logging.info("Order for symol: " + symbol + " for quantity " + str(quantity) + " placed at price " + str(tradePrice) + " .Order no is:" + str(orderNo)) return orderNo except kiteexceptions.TokenException as e: self.DumpExceptionInfo(e, "SellMISOrder") logging.info("Initialising kite again...") print "Initialising kite again..." self.InitialiseKite() return "" def GetOrderHistory(self, orderNo): try: orderHistory = self.kite.order_history(orderNo) return orderHistory except kiteexceptions.TokenException as e: self.DumpExceptionInfo(e, "GetOrderHistory") logging.info("Initialising kite again...") print "Initialising kite again..." self.InitialiseKite() orderHistory = self.kite.order_history(orderNo) return orderHistory return [] def GetOrders(self): try: return self.kite.orders() except kiteexceptions.TokenException as e: self.DumpExceptionInfo(e, "GetOrders") logging.info("Initialising kite again...") print "Initialising kite again..." self.InitialiseKite() return self.kite.orders() def ModifyBOTpOrder(self, orderId, price): try: self.kite.modify_order(variety='bo', order_id=orderId, price=price) except kiteexceptions.TokenException as e: self.DumpExceptionInfo(e, "ModifyBOTpOrder") logging.info("Initialising kite again...") print "Initialising kite again..." self.InitialiseKite() self.kite.modify_order(variety='bo', order_id=orderId, price=price) def ModifyBOSlOrder(self, orderId, triggerPrice): try: self.kite.modify_order(variety='bo', order_id=orderId, trigger_price=triggerPrice) except kiteexceptions.TokenException as e: self.DumpExceptionInfo(e, "ModifyBOSlOrder") logging.info("Initialising kite again...") print "Initialising kite again..." self.InitialiseKite() self.kite.modify_order(variety='bo', order_id=orderId, trigger_price=triggerPrice) def GetHistoricalData(self, instrumentToken, fromDate, toDate, interval, continuous): try: # from date/to date : yyyy-mm-dd HH:MM:SS return self.kite.historical_data(instrumentToken, fromDate, toDate, interval, continuous) except Exception as e: self.DumpExceptionInfo(e, "GetHistoricalData") def DumpExceptionInfo(self, e, funcName): logging.error("Error in KiteOrderManager::" + funcName, exc_info=True) print e print "Error in KiteOrderManager::" + funcName
class Gen_Pnf_With_Zerodha_Kite_Data: """ This class generates point and figure chart after extracting data from zerodha kite historical api. """ def __init__(self): self.__credentials = KITE_API_KEY_ACCESS_TOKEN.get_kite_credentials() self.__config = ( pd.read_excel('settings/dhelm_pnf_chart_gen_settings.xlsx')) self.__client = KiteConnect(self.__credentials[0]) self.__client.set_access_token(self.__credentials[1]) self.__from_date = ( self.__config.at[self.__config.first_valid_index(), 'from_dt']).strftime("%Y-%m-%d %H:%M:%S") self.__to_date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") self.__list_stocks = pd.read_csv('settings/kite_chart_gen_list.csv') if self.__config.at[self.__config.first_valid_index(), 'method_percentage']: self.__box_type = Types.Method_percentage else: self.__box_type = Types.Method_value if 'close' in self.__config.at[self.__config.first_valid_index(), 'calculation_method']: self.__calculation_method = Types.Method_close else: self.__calculation_method = Parameters.Types.Method_highlow self.__box_size = (self.__config.at[self.__config.first_valid_index(), 'BOX_SIZE']) self.__reversal = (self.__config.at[self.__config.first_valid_index(), 'REVERSAL']) self.__box_percentage = ( self.__config.at[self.__config.first_valid_index(), 'BOX_PERCENTAGE']) self.__folder = 'charts_kite' for index, row in self.__list_stocks.iterrows(): self.__data_historical = self.__get_historical_data(row) print('Generating point and figure chart for ' + row['tradingsymbol']) ChartGenerator.gen_chart(self.__data_historical, row['tradingsymbol'], row['exchange'], self.__box_type, self.__calculation_method, self.__reversal, self.__box_size, self.__box_percentage, self.__folder) print('DONE..Check for chart in the folder ' + self.__folder + '.') def __get_historical_data(self, row): hist = None df = pd.DataFrame() try: hist = self.__client.historical_data(int(row['instrument_token']), self.__from_date, self.__to_date, 'day', False) except requests.exceptions.ReadTimeout: pass except exceptions.NetworkException: pass except Exception: pass if hist is not None: for entry in hist: if 'date' in entry: entry['date'] = str(entry['date']) col = Counter() for k in list(hist): col.update(k) df = pd.DataFrame([k.values() for k in hist], columns=col.keys()) return df
def start(name, date, access_token, interval): # print("Starting Trading Engine...", flush=True) config = configparser.ConfigParser() # path = os.getcwd() path = '/home/ubuntu/APT/APT/Simulation' config_path = path + '/config.ini' config.read(config_path) api_key = config['API']['API_KEY'] kite = KiteConnect(api_key=api_key) kite.set_access_token(access_token) os.chdir(path) print("Connection Successful") scrip_dict = { 'ADANIPORTS': '3861249', 'ASIANPAINT': '60417', 'AXISBANK': '1510401', 'BAJAJ-AUTO': '4267265', 'BAJFINANCE': '81153', 'BAJAJFINSV': '4268801', 'BPCL': '134657', 'BHARTIARTL': '2714625', 'INFRATEL': '7458561', 'BRITANNIA': '140033', 'CIPLA': '177665', 'COALINDIA': '5215745', 'DRREDDY': '225537', 'EICHERMOT': '232961', 'GAIL': '1207553', 'GRASIM': '315393', 'HCLTECH': '1850625', 'HDFCBANK': '341249', 'HEROMOTOCO': '345089', 'HINDALCO': '348929', 'HINDUNILVR': '356865', 'HDFC': '340481', 'ICICIBANK': '1270529', 'ITC': '424961', 'IBULHSGFIN': '7712001', 'IOC': '415745', 'INDUSINDBK': '1346049', 'INFY': '408065', 'JSWSTEEL': '3001089', 'KOTAKBANK': '492033', 'LT': '2939649', 'M&M': '519937', 'MARUTI': '2815745', 'NTPC': '2977281', 'ONGC': '633601', 'POWERGRID': '3834113', 'SBIN': '779521', 'SUNPHARMA': '857857', 'TCS': '2953217', 'TATAMOTORS': '884737', 'TATASTEEL': '895745', 'TECHM': '3465729', 'TITAN': '897537', 'UPL': '2889473', 'ULTRACEMCO': '2952193', 'VEDL': '784129', 'WIPRO': '969473', 'YESBANK': '3050241', 'ZEEL': '975873', 'RELIANCE': '738561' } def prev_weekday(adate): adate -= timedelta(days=1) while adate.weekday() > 4: adate -= timedelta(days=1) return adate prev_date = prev_weekday(datetime.datetime.strptime(date, "%Y-%m-%d").date()) data = kite.historical_data(instrument_token=int(scrip_dict[name]), from_date=date, to_date=date, interval=interval) data = pd.DataFrame(data) prev_day_data = kite.historical_data(instrument_token=int(scrip_dict[name]), from_date=prev_date, to_date=prev_date, interval='day') prev_day_data = pd.DataFrame(prev_day_data) prev_day_data.columns = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume'] prev_day_data.to_csv("previous_day_data_" + name + '.csv') for i in range(len(data)): single_candle = data.iloc[[i]] single_candle.to_csv('ohlc_data_' + name +'.csv',index= False) print(single_candle, flush= True) time.sleep(60)
stock_name_string) print(stock_name_string, flush=True) # Establicsh connection with Kiteconnect config = configparser.ConfigParser() config.read(config_path) api_key = config['API']['API_KEY'] kite = KiteConnect(api_key=api_key) kite.set_access_token(access_token) # Extract Last day's daily level ohlc data date_from = prev_weekday(date.today()) date_to = date_from interval = 'day' previous_day_data = kite.historical_data(instrument_token=token[0], from_date=date_from, to_date=date_to, interval=interval) previous_day_data = pd.DataFrame(previous_day_data) previous_day_data.columns = [ 'Date', 'Open', 'High', 'Low', 'Close', 'Volume' ] previous_day_data.to_csv("previous_day_data_" + name + '.csv') # Sleep till 9:15 time_now = datetime.now() sleep_time = 60 - time_now.second time.sleep(sleep_time) time_now = datetime.now() print('Script Started at ' + str(time_now), flush=True) #Start Threading