def ticker_service(): kite = KiteConnect(api_key=api_key) kite.set_access_token(access_token) kws = KiteTicker(api_key, access_token) tokens = [138098692] def on_ticks(ws, ticks): pprint(ticks) # Callback for successful connection. def on_connect(ws, response): logging.info("Successfully connected. Response: {}".format(response)) ws.subscribe(tokens) ws.set_mode(ws.MODE_FULL, tokens) logging.info("Subscribe to tokens in Full mode: {}".format(tokens)) # 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 # Infinite loop on the main thread. Nothing after this will run. # You have to use the pre-defined callbacks to manage subscriptions. kws.connect(threaded=True) return kws
def startTicker(self): brokerAppDetails = self.brokerLogin.getBrokerAppDetails() accessToken = self.brokerLogin.getAccessToken() if accessToken == None: logging.error('ZerodhaTicker startTicker: Cannot start ticker as accessToken is empty') return ticker = KiteTicker(brokerAppDetails.appKey, accessToken) ticker.on_connect = self.on_connect ticker.on_close = self.on_close ticker.on_error = self.on_error ticker.on_reconnect = self.on_reconnect ticker.on_noreconnect = self.on_noreconnect ticker.on_ticks = self.on_ticks ticker.on_order_update = self.on_order_update logging.info('ZerodhaTicker: Going to connect..') self.ticker = ticker self.ticker.connect(threaded=True)
def startTicker(): userConfig = getUserConfig() accessToken = getAccessToken() if accessToken == None: logging.error( 'startTicker: Cannot start ticker as accessToken is empty') return global ticker ticker = KiteTicker(userConfig['apiKey'], accessToken) ticker.on_connect = onConnect ticker.on_close = onDisconnect ticker.on_error = onError ticker.on_reconnect = onReconnect ticker.on_noreconnect = onMaxReconnectsAttempt ticker.on_ticks = onNewTicks ticker.on_order_update = onOrderUpdate logging.info('Ticker: Going to connect..') ticker.connect(threaded=True)
def GetTickerData(access_token, tokens): kws = KiteTicker('hr1osvvapq449uqf', access_token) # tokens = [11005954] kws.on_ticks = on_ticks kws.on_close = on_close kws.on_error = on_error kws.on_connect = partial(on_connect, tokens) kws.on_reconnect = on_reconnect kws.on_noreconnect = on_noreconnect kws.connect(threaded=True, disable_ssl_verification=True) logging.info( "This is main thread. Will change webosocket mode every 5 seconds.") count = 0 while True: if kws.is_connected(): kws.set_mode(kws.MODE_QUOTE, tokens) time.sleep(1)
def on_connect(ws, response): # Callback on successful connect. # Subscribe to a list of instrument_tokens (RELIANCE and ACC here). ws.subscribe(instruments.keys()) # Set RELIANCE to tick in `full` mode. ws.set_mode(ws.MODE_FULL, instruments.keys()) def on_close(ws, code, reason): # On connection close stop the main loop # Reconnection will not happen after executing `ws.stop()` print('Connection closed:', code, reason) def on_error(ws, code, reason): # On connection close stop the main loop # Reconnection will not happen after executing `ws.stop()` print('Connection error:', code, reason) # Assign the callbacks. kws.on_ticks = on_ticks kws.on_connect = on_connect kws.on_close = on_close kws.on_error = on_error # Infinite loop on the main thread. Nothing after this will run. # You have to use the pre-defined callbacks to manage subscriptions. kws.connect()
def run(self): tokens = self.tokens kws = KiteTicker('0ld4qxtvnif715ls', self.access_token) def stop_gracefully(): kws.stop_retry() kws.close() print( '____________________Closed KiteTicker Gracefully_________________' ) def on_ticks(ws, ticks): print( '\n______________________________ON TICKS_____________________________\n' ) for i in ticks: t = i['instrument_token'] self.global_data[t]['price'] = i['last_price'] try: self.global_data[t]['volume'] = i['volume'] except: pass strategy_meta = dict() strategy_group_meta = dict() for s in self.strat_list: t = int(s.instrument) self.strategy_status(s) # strategy_meta[str(s)] = { # 'criteria' : s.cond_str(), # 'status' : str(self.strat_data[s.pk]['status']), # 'timestamp' : self.strat_data[s.pk]['timestamp'], # 'price' : str(self.global_data[t]['price']), # # 'volume' : str(self.global_data[t]['volume']) , # 'indicator 1' : str(self.strat_data[s.pk]['indicator1']) + "<br>"+ str(s.indicator1) +"" , # 'indicator 2' : str(self.strat_data[s.pk]['indicator2']) + "<br>"+ str(s.indicator2) +"" # } for sg in self.strat_group_list: self.strat_group_status(sg) strategy_group_meta[str(sg)] = { # 'status' : str(self.strat_group[sg.pk]['status']), 'timestamp': self.strat_group[sg.pk]['timestamp'], 'eval': self.strat_group[sg.pk]['eval'] } if (self.strat_group[sg.pk]['status']): if (sg.entry_condition == 'Buy'): strategy_group_meta[str(sg)]['color'] = '#00FF00' else: strategy_group_meta[str(sg)]['color'] = '#FF0000' else: strategy_group_meta[str(sg)]['color'] = '#9CE9F9' df = pd.DataFrame(strategy_group_meta) new_columns = df.columns[(df.ix['timestamp']).argsort()] df = df[new_columns[::-1]] strategy_group_meta = df.to_dict() data_to_send = {'strategy_group_meta': strategy_group_meta} self.task.update_state(state='PROGRESS', meta=data_to_send) print(data_to_send) print('\n------\n') # print(strategy_group_meta) if (self.tick_count == 0): if (get_refresh(self.user.pk)): print("\nStrategy Refreshing needed.....") stop_gracefully() self.strat_refresh() self.strat_group_refresh() self.run() set_refresh(self.user.pk, False) self.tick_count = (self.tick_count + 1) % 10 def on_connect(ws, response): logging.info( "Successfully connected. Response: {}".format(response)) ws.subscribe(tokens) ws.set_mode(ws.MODE_FULL, tokens) print("Subscribe to tokens in Full mode: {}".format(tokens)) def on_close(ws, code, reason): print("Connection closed: {code} - {reason}".format(code=code, reason=reason)) # print("Connection closed") def on_error(ws, code, reason): print("Connection error: {code} - {reason}".format(code=code, reason=reason)) # print("Connection Error") def on_reconnect(ws, attempts_count): # logging.info("Reconnecting: {}".format(attempts_count)) print("Reconnecting") def on_noreconnect(ws): print("Reconnect failed.") 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 kws.connect(threaded=False)
def main(): print "Executing CBO Algo for Equities" print "-------------------------------" global kite global fno_dict, base_dict, config_dict, orders global scrip_map, sub_list global order_dict inst_token = [] #TODO: Add argparser for validating input if len(sys.argv) < NO_OF_PARAMS: print "Invalid number of params" #return # read config file config_dict = utils.read_config_file() # get list of fno fno_dict = utils.get_fno_dict() # get yesterdays high low base_dict = get_yesterdays_ohlc(sys.argv[1]) #get kite object api_key, access_token, kite = kite_utils.login_kite(None) # get instrument list, create quote subscription list and # mapping between instrument token and tradingsymbol quote_list = [] data = kite.instruments("NSE") for each in fno_dict: for instrument in data: if each == instrument['tradingsymbol']: entry = "NSE:" + str(instrument['tradingsymbol']) quote_list.append(entry) # sub list for subscribing to the quotes sub_list.append(int(instrument['instrument_token'])) #mapping dictionary for token and trading symbol scrip_map[int(instrument['instrument_token'])] = str(instrument['tradingsymbol']) print scrip_map # open file to write buy/sell orders fp = open(config_dict['cbo_seed_file'], "w") # write header utils.write_header(fp, "CBO") # Generate order file count = int(0) quotes = kite.quote(quote_list) for each in quotes: scrip = each.split(":")[1].strip("\n") if scrip not in base_dict: continue if float(quotes[each]["ohlc"]["open"]) < float(config_dict['start_price']): continue if float(quotes[each]["ohlc"]["open"]) > float(config_dict['end_price']): continue count = int(count) + int(1); buy, sell = generate_orders(scrip, base_dict[scrip], quotes[each]['ohlc']['open']) if (buy != None): fp.write(buy) if (sell != None): fp.write(sell) fp.close() # create dictionary for active orders curr_order = kite.orders() print "------------------------------------------------" print curr_order print "------------------------------------------------" # push all the orders order_list = [] order_dict = {} fp = open(config_dict['cbo_seed_file']) for each in fp: #ignore line starting with # if each.startswith("#"): continue each = each.rstrip() line = each.split(" ") scrip = line[SCRIP_ID] action = line[ACTION_ID] price = line[PRICE_ID] t_price = line[TRIGGER_ID] target = line[TARGET_ID] stoploss = line[STOPLOSS_ID] live_price = line[LIVE_PRICE_ID] if line[SCRIP_ID] not in order_dict: order_dict[scrip] = {} order_dict[scrip][action] = {} else: order_dict[scrip][action] = {} order_dict[scrip][action]['price'] = price order_dict[scrip][action]['trigger_price'] = t_price order_dict[scrip][action]['target'] = target order_dict[scrip][action]['stoploss'] = stoploss order_dict[scrip][action]['flag'] = 0 order_dict[scrip][action]['live_price'] = live_price fp.close() print "----------------------------------------------------------------" print order_dict print "----------------- End of order list ----------------------------" kws = KiteTicker(api_key, access_token, debug=False) kws.on_ticks = on_ticks kws.on_connect = on_connect kws.on_close = on_close kws.on_error = on_error kws.on_noreconnect = on_noreconnect kws.on_reconnect = on_reconnect kws.on_order_update = on_order_update kws.connect()
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")
def process_ohlc(api_key, access_token, token, timeframe): #Call the Global Exchangable Variable global data_ohlc # Initialise Kite Socket Connection print("Initialising Kite Ticker") kws = KiteTicker(api_key, access_token) process_ohlc.tick_df = pd.DataFrame(columns=['Token', 'Timestamp', 'LTP'], index=pd.to_datetime([])) process_ohlc.last_saved_time = 10 def on_ticks(ws, 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): #Check if its a 5th minute if (ticks[0]['timestamp'].minute() % 5 == 0) and (ticks[0]['timestamp'].minute() != process_ohlc.last_saved_time): process_ohlc.tick_df = pd.DataFrame( columns=['Token', 'Timestamp', 'LTP'], index=pd.to_datetime([])) #Append Ticks into 1 table process_ohlc.tick_df = process_ohlc.tick_df.append( { 'Token': ticks[0]['instrument_token'], 'Timestamp': ticks[0]['timestamp'], 'LTP': ticks[0]['last_price'] }, ignore_index=True) # set timestamp as index process_ohlc.tick_df = process_ohlc.tick_df.set_index( ['Timestamp']) process_ohlc.tick_df['Timestamp'] = pd.to_datetime( process_ohlc.tick_df.index, unit='s') # convert to OHLC format data_ohlc_raw = process_ohlc.tick_df['LTP'].resample( timeframe).ohlc() data_ohlc_raw['Last_Time'] = process_ohlc.tick_df['Timestamp'][ len(process_ohlc.tick_df) - 1] data_ohlc = data_ohlc_raw 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")
def run(self): tokens = self.tokens kws = KiteTicker('0ld4qxtvnif715ls', self.access_token) def stop_gracefully(): kws.stop_retry() kws.close() print( '____________________Closed KiteTicker Gracefully_________________' ) def on_ticks(ws, ticks): print( '\n______________________________ON TICKS_____________________________\n' ) for i in ticks: t = i['instrument_token'] self.global_data[t]['price'] = i['last_price'] self.global_data[t]['volume'] = i['volume'] strategy_meta = dict() strategy_group_meta = dict() for s in self.strat_list: t = int(s.instrument) self.strategy_status(s) strategy_meta[str(s)] = { 'criteria': s.cond_str(), 'status': str(self.strat_data[s.pk]['status']), 'timestamp': self.strat_data[s.pk]['timestamp'], 'price': str(self.global_data[t]['price']), # 'volume' : str(self.global_data[t]['volume']) , 'indicator 1': str(self.strat_data[s.pk]['indicator1']) + "<br>" + str(s.indicator1) + "", 'indicator 2': str(self.strat_data[s.pk]['indicator2']) + "<br>" + str(s.indicator2) + "" } for sg in self.strat_group_list: self.strat_group_status(sg) strategy_group_meta[str(sg)] = { 'status': str(self.strat_group[sg.pk]['status']), 'exp': self.strat_group[sg.pk]['exp'], 'eval': self.strat_group[sg.pk]['eval'] } df = pd.DataFrame(strategy_meta) new_columns = df.columns[(df.ix['timestamp']).argsort()] df = df[new_columns[::-1]] strategy_meta = df.to_dict() self.task.update_state(state='PROGRESS', meta={ 'strategy_meta': strategy_meta, 'strategy_group_meta': strategy_group_meta }) # print(strategy_meta) print('\n------\n') print(strategy_group_meta) if (self.tick_count == 0): r = Refreshed.objects.all().filter(name='Strategy') if (len(r) > 0): #Strategies were modified print("\nStrategy Refreshing needed.....") stop_gracefully() self.strat_refresh() self.run() r.delete() r = Refreshed.objects.all().filter(name='Strategy_Group') if (len(r) > 0): #Strategies were modified print("\nnStrategy Group Refreshing needed.....") self.strat_group_refresh() r.delete() self.tick_count = (self.tick_count + 1) % 10 def on_connect(ws, response): logging.info( "Successfully connected. Response: {}".format(response)) ws.subscribe(tokens) ws.set_mode(ws.MODE_FULL, tokens) print("Subscribe to tokens in Full mode: {}".format(tokens)) def on_close(ws, code, reason): print("Connection closed: {code} - {reason}".format(code=code, reason=reason)) # print("Connection closed") def on_error(ws, code, reason): print("Connection error: {code} - {reason}".format(code=code, reason=reason)) # print("Connection Error") def on_reconnect(ws, attempts_count): # logging.info("Reconnecting: {}".format(attempts_count)) print("Reconnecting") def on_noreconnect(ws): print("Reconnect failed.") 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 kws.connect(threaded=False)
def main(): print "Executing CBO Algo for Equities" print "-------------------------------" global fno_dict global base_dict global config_dict global orders global sub_list global fno_mapping global order_dict #TODO: Add argparser for validating input if len(sys.argv) < NO_OF_PARAMS: print "Invalid number of params" return # read config file config_dict = utils.read_config_file() # get list of fno fno_dict = utils.get_fno_dict() # get yesterdays high low base_dict = get_yesterdays_fno_ohlc(sys.argv[1]) #simulate(sys.argv[2]) #open kite connection if len(sys.argv) == int(NO_OF_PARAMS) + int(1): request_token = sys.argv[2] else: request_token = None #api_key, access_token, kite = kite_utils.kite_login(request_token) # get instrument list quote_list = [] data = kite.instruments("NFO") for each in data: if each['instrument_type'] != 'FUT': continue if config_dict['contract_str'] not in each['tradingsymbol']: continue entry = "NFO:" + str(each['tradingsymbol']) quote_list.append(entry) sub_list.append(int(each['instrument_token'])) fno_mapping[int(each['instrument_token'])] = str(each['tradingsymbol']) print "==============================" print fno_mapping print "==============================" # open file to write buy/sell orders fp = open(config_dict['cbo_fno_seed_file'], "w") count = int(0) quotes = kite.quote(quote_list) for each in quotes: scrip = each.split(":")[1].strip("\n") m = re.search("\d", scrip) if m: scrip = scrip[:m.start()] if float(quotes[each]["ohlc"]["open"]) < float( config_dict['start_price']): continue if float(quotes[each]["ohlc"]["open"]) > float( config_dict['end_price']): continue count = int(count) + int(1) if scrip in base_dict: scrip_fno = scrip + "18MARFUT" print scrip_fno buy, sell = generate_orders(scrip, base_dict[scrip], quotes[each]['ohlc']['open']) if (buy != None): buy_dict = {} each = buy.split(" ") buy_dict['price'] = each[2] buy_dict['target'] = float( utils.get_floating_value(float(each[2]) + float(each[4]))) buy_dict['stoploss'] = float( utils.get_floating_value(float(each[2]) - float(each[5]))) buy_dict['trade_active'] = False order_dict[scrip_fno] = {} order_dict[scrip_fno]['buy'] = buy_dict fp.write(buy) if (sell != None): sell_dict = {} each = sell.split(" ") sell_dict['price'] = each[2] sell_dict['target'] = float( utils.get_floating_value(float(each[2]) - float(each[4]))) sell_dict['stoploss'] = float( utils.get_floating_value(float(each[2]) + float(each[5]))) sell_dict['trade_active'] = False order_dict[scrip_fno]['sell'] = sell_dict fp.write(sell) fp.close() print "-------------------------------------------------------" print order_dict print "-------------------------------------------------------" kws = KiteTicker(api_key, access_token, debug=False) kws.on_ticks = on_ticks kws.on_connect = on_connect kws.on_close = on_close kws.on_error = on_error kws.on_noreconnect = on_noreconnect kws.on_reconnect = on_reconnect kws.on_order_update = on_order_update kws.connect()