def start_ticker(tokens, history, auth='', callback=None): kws = KiteTicker("kitefront", "wPXXjA5tJE8KJyWN753rbGnf5lXlzU0Q") kws.socket_url = "wss://ws.zerodha.com/?api_key=kitefront&user_id=MK4445&public_token=wPXXjA5tJE8KJyWN753rbGnf5lXlzU0Q&uid=1587463057403&user-agent=kite3-web&version=2.4.0" def on_ticks(ws, ticks): for tick in ticks: tick['lastPrice'] = tick['last_price'] tick['token'] = tick['instrument_token'] tick['time'] = int(datetime.now().timestamp()) dataFeed.notify(tick) def on_connect(ws, response): print("Subscribing to tokens: ", storage['tokens']) ws.subscribe(storage['tokens']) def on_close(ws, code, reason): pass kws.on_ticks = on_ticks kws.on_connect = on_connect kws.on_close = on_close while (True): if (storage.get('continueMain')): break time.sleep(2) dataManager.load_data(list(storage['tokens'])) print("History loaded") print("WebSocket Connecting") kws.connect()
def StartTicker(): tokenManager = TokenManager.GetInstance() kws = KiteTicker(tokenManager.GetApiKey(), tokenManager.GetAccessToken()) # Assign the callbacks. kws.on_ticks = on_ticks kws.on_connect = on_connect kws.on_close = on_close kws.on_message = on_message kws.connect()
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 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 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)
prevFast = df['ema12'][-1] prevSlow = df['ema50'][-1] nowFast = df['ema12'][-2] nowSlow = df['ema50'][-2] print("Previous Candle FastSlow: ", prevFast, prevSlow) print("Current Candle FastSlow: ", nowFast, nowSlow) if (nowFast > nowSlow ) and (prevFast < prevSlow): print("Long Breakout") elif (nowFast < nowSlow ) and (prevFast > prevSlow): print("Short Breakout") else: print("No Breakout") def on_connect(ws, response): # Callback on successful connect. ws.subscribe([14350850]) ws.set_mode(ws.MODE_FULL, [14350850]) def on_close(ws, code, reason): # On connection close stop the event loop. # Reconnection will not happen after executing `ws.stop()` ws.stop() print("Run loop") kiteTicker.on_ticks = on_ticks kiteTicker.on_connect = on_connect kiteTicker.on_close = on_close kiteTicker.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'] 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 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 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 initial_setup(): global s, u, data, kws, loop try: logged_in = False stored_api_key = read_key_from_settings('api_key') stored_access_token = read_key_from_settings('access_token') if stored_access_token is not None and stored_api_key is not None: print( 'You already have a stored access token: [%s] paired with API key [%s]' % (stored_access_token, stored_api_key)) try: u = KiteConnect(api_key=stored_api_key) u.set_access_token(stored_access_token) kws = KiteTicker(stored_api_key, stored_access_token) u.profile() logged_in = True except KiteException.TokenException as e: print('Sorry, there was an error [%s]. Let' 's start over\n\n' % e) if logged_in is False: stored_api_key = read_key_from_settings('api_key') if stored_api_key is None: stored_api_key = input('What is your app' 's API key [%s]: ' % stored_api_key) write_key_to_settings('api_key', stored_api_key) stored_api_secret = read_key_from_settings('api_secret') if stored_api_secret is None: stored_api_secret = input('What is your app' 's API secret [%s]: ' % stored_api_secret) write_key_to_settings('api_secret', stored_api_secret) stored_redirect_uri = read_key_from_settings('redirect_uri') if stored_redirect_uri is None: stored_redirect_uri = input('What is your app' 's redirect_uri [%s]: ' % stored_redirect_uri) write_key_to_settings('redirect_uri', stored_redirect_uri) stored_username = read_key_from_settings('username') if stored_username is None: stored_username = input('What is your Zerodha username: '******'username', stored_username) stored_password = read_key_from_settings('password') if stored_password is None: stored_password = input('What is your Zerodha password: '******'password', stored_password) stored_password2fa = read_key_from_settings('password2fa') if stored_password2fa is None: stored_password2fa = input('What is your Zerodha Pin: ') write_key_to_settings('password2fa', stored_password2fa) u = KiteConnect(api_key=stored_api_key) print('URL: %s\n' % u.login_url()) try: print("Trying to authenticate") token = authenticate(u.login_url(), stored_username, stored_password, stored_password2fa) print("Token: {0}".format(token)) except SystemError as se: print('Uh oh, there seems to be something wrong. Error: [%s]' % se) return print("Api secret: {0}".format(stored_api_secret)) data = u.generate_session(token, api_secret=stored_api_secret) print("Data: {0}".format(data)) write_key_to_settings('access_token', data['access_token']) u.set_access_token(data['access_token']) kws = KiteTicker(stored_api_key, data['access_token']) # kws = KiteTicker(stored_api_key, stored_access_token) # kws.on_ticks = on_ticks kws.on_connect = on_connect kws.on_close = on_close kws.connect(threaded=True) while True: def on_ticks(ws, ticks): print("Ticks= {}".format(ticks)) helper_method(ticks) def helper_method(ticks): print("Inside helper function") filename = os.path.join(os.path.dirname(__file__), "Zerodha Instruments.xlsx") pythoncom.CoInitialize() app = xw.App(visible=False) wb = app.books.open(filename) ws = wb.sheets['Watchlist'] df = pd.read_excel(filename, sheet_name='Watchlist') instrument_tokens_list = df['instrument_token'].tolist() for tick in ticks: if tick['instrument_token'] in instrument_tokens_list: pos = instrument_tokens_list.index( tick['instrument_token']) cell = 'E' + str(pos + 2) ws.range(cell).value = tick['last_price'] # Code to place an order # transact_type_cell = 'N' + str(pos + 2) # transact_type = ws.range(transact_type_cell).value # trading_symbol_cell = 'C' + str(pos + 2) # trading_symbol = ws.range(trading_symbol_cell).value # quantity_cell = 'O' + str(pos + 2) # quantity = ws.range(quantity_cell).value # # if transact_type == 'buy': # if trading_symbol == 'NSE': # u.place_order(tradingsymbol=trading_symbol, exchange=u.EXCHANGE_NSE, # transaction_type=u.TRANSACTION_TYPE_BUY, quantity=quantity, # order_type=u.ORDER_TYPE_MARKET, product=u.PRODUCT_NRML) # # elif trading_symbol == 'BSE': # u.place_order(tradingsymbol=trading_symbol, exchange=u.EXCHANGE_BSE, # transaction_type=u.TRANSACTION_TYPE_BUY, quantity=quantity, # order_type=u.ORDER_TYPE_MARKET, product=u.PRODUCT_NRML) # # elif trading_symbol == 'MCX': # u.place_order(tradingsymbol=trading_symbol, exchange=u.EXCHANGE_MCX, # transaction_type=u.TRANSACTION_TYPE_BUY, quantity=quantity, # order_type=u.ORDER_TYPE_MARKET, product=u.PRODUCT_NRML) # # elif trading_symbol == 'NFO': # u.place_order(tradingsymbol=trading_symbol, exchange=u.EXCHANGE_NFO, # transaction_type=u.TRANSACTION_TYPE_BUY, quantity=quantity, # order_type=u.ORDER_TYPE_MARKET, product=u.PRODUCT_NRML) # # elif transact_type == 'sell': # if trading_symbol == 'NSE': # u.place_order(tradingsymbol=trading_symbol, exchange=u.EXCHANGE_NSE, # transaction_type=u.TRANSACTION_TYPE_SELL, quantity=quantity, # order_type=u.ORDER_TYPE_MARKET, product=u.PRODUCT_NRML) # # elif trading_symbol == 'BSE': # u.place_order(tradingsymbol=trading_symbol, exchange=u.EXCHANGE_NSE, # transaction_type=u.TRANSACTION_TYPE_SELL, quantity=quantity, # order_type=u.ORDER_TYPE_MARKET, product=u.PRODUCT_NRML) # # elif trading_symbol == 'MCX': # u.place_order(tradingsymbol=trading_symbol, exchange=u.EXCHANGE_MCX, # transaction_type=u.TRANSACTION_TYPE_SELL, quantity=quantity, # order_type=u.ORDER_TYPE_MARKET, product=u.PRODUCT_NRML) # # elif trading_symbol == 'NFO': # u.place_order(tradingsymbol=trading_symbol, exchange=u.EXCHANGE_NFO, # transaction_type=u.TRANSACTION_TYPE_SELL, quantity=quantity, # order_type=u.ORDER_TYPE_MARKET, product=u.PRODUCT_NRML) # # ws.range(transact_type_cell).value = "" # ws.range(quantity_cell).value = "" wb.save(filename) app.quit() kws.on_ticks = on_ticks except Exception as error: print("Error {0}".format(str(error))) exit(0)
def startTicker(q): logging.info( 'starting threaded websocket connection, loading initial state') # Initialise global access_token_A access_token_A = ReadAccessTokenFile(access_token_A_file) #global access_token_B #access_token_B=ReadAccessTokenFile(access_token_B_file) global kws kws = KiteTicker(api_key_A, access_token_A) #setting queue for DB update qDB = Queue() #put df in queue #jobReconnect() global df #if oracle_db.dialect.has_table(oracle_db, 's3stockmaster'): # df=jobImportDB() # logging.info('putting db imported dataframe in multiprocessing queue on RAM') # q.put(df) #else: # pass # print('does not exist') qDB.put(1) kws.on_ticks = on_ticks kws.on_connect = on_connect kws.on_close = on_close kws.connect(threaded=True) flagMargin = False flagStartOver = False counterStockTick = 0 df['profit'] = 0 df['rank'] = 0 df['rank2'] = 0 df['loser'] = 0 df['skip'] = 0 df['buy'] = 0 df['sell'] = 0 df['high'] = 0 df['low'] = 0 #t = timer() global df_original df_original = df while True: #index and make changes in a copy of df called df_calc df_calc = df df_calc = df_calc.set_index('instrument_token') #traverse dataframe for index, row in df_calc.iterrows(): #set base buy and sell quantity if df_calc.loc[index, 'action'] == 'BaseSet': pass #identify the stock to be traded elif df_calc.loc[index, 'action'] == 'StockSelect': if df_calc.loc[index, 'rank'] == 1 and df_calc.loc[index, 'v'] >= 2: df_calc.at[index, 'qty'] = math.floor( 344 / df_calc.loc[index, 'ltp'] * df_calc.loc[index, 'x']) df_calc.at[index, 'action'] = 'Start' elif df_calc.loc[index, 'rank'] == 1 and df_calc.loc[index, 'v'] < 2: flagStartOver = True #place order on zerodha for the selected trade elif df_calc.loc[index, 'action'] == 'Start': if skip_kite == False: if direction_switch == True: df_calc.at[index, 'id_a_sell'] = placeMarketOrder( api_key_A, access_token_A, 'SELL', df_calc.loc[index, 'zid'], df_calc.loc[index, 'qty']) df_calc.at[index, 'sl'] = 1.003 * df_calc.loc[index, 'ltp'] else: df_calc.at[index, 'id_a_buy'] = placeMarketOrder( api_key_A, access_token_A, 'BUY', df_calc.loc[index, 'zid'], df_calc.loc[index, 'qty']) df_calc.at[index, 'sl'] = 0.997 * df_calc.loc[index, 'ltp'] df_calc.at[index, 'action'] = 'VerifyStart' df_calc.at[index, 'pExec'] = df_calc.loc[index, 'ltp'] #verify if the initial zerodha order is completed elif df_calc.loc[index, 'action'] == 'VerifyStart': if skip_kite == False: if direction_switch == True: status = checkExecutionStatus( api_key_A, access_token_A, df_calc.loc[index, 'id_a_sell']) if status == "COMPLETE": df_calc.at[index, 'id_a_buy'] = placeLimitOrder( api_key_A, access_token_A, 'BUY', df_calc.loc[index, 'zid'], df_calc.loc[index, 'qty'], round(0.997 * df_calc.loc[index, 'ltp'], 1)) df_calc.at[index, 'action'] = 'RunTrade' elif status == "REJECTED": df_calc.at[index, 'action'] = 'FatalError' else: status = checkExecutionStatus( api_key_A, access_token_A, df_calc.loc[index, 'id_a_buy']) if status == "COMPLETE": df_calc.at[index, 'id_a_sell'] = placeLimitOrder( api_key_A, access_token_A, 'SELL', df_calc.loc[index, 'zid'], df_calc.loc[index, 'qty'], round(1.003 * df_calc.loc[index, 'ltp'], 1)) df_calc.at[index, 'action'] = 'RunTrade' elif status == "REJECTED": df_calc.at[index, 'action'] = 'FatalError' else: df_calc.at[index, 'action'] = 'RunTrade' elif df_calc.loc[index, 'action'] == 'ExitManual': pass #verify if the closing zerodha order is completed elif df_calc.loc[index, 'action'] == 'RunTrade': if skip_kite == False: slflag = 0 if direction_switch == True: if df_calc.loc[index, 'ltp'] > df_calc.loc[index, 'sl']: #df_calc.at[index,'id_a_buy']=placeMarketOrder(api_key_A,access_token_A,'BUY',df_calc.loc[index,'zid'],df_calc.loc[index,'qty']) #df_calc.at[index,'action']='TradeComplete' df_calc.at[index, 'action'] = 'ExitManual' slflag = 1 else: if df_calc.loc[index, 'ltp'] < df_calc.loc[index, 'sl']: #df_calc.at[index,'id_a_sell']=placeMarketOrder(api_key_A,access_token_A,'SELL',df_calc.loc[index,'zid'],df_calc.loc[index,'qty']) #df_calc.at[index,'action']='TradeComplete' df_calc.at[index, 'action'] = 'ExitManual' slflag = 1 if slflag == 0: if direction_switch == True: status = checkExecutionStatus( api_key_A, access_token_A, df_calc.loc[index, 'id_a_buy']) else: status = checkExecutionStatus( api_key_A, access_token_A, df_calc.loc[index, 'id_a_sell']) if status == "COMPLETE": df_calc.at[index, 'action'] = 'TradeComplete' elif status == "REJECTED": df_calc.at[index, 'action'] = 'FatalError' else: df_calc.at[index, 'action'] = 'TradeComplete' #trade completed on zerodha, start over elif df_calc.loc[index, 'action'] == 'TradeComplete': df_calc.at[index, 'skip'] = 0 #skip 1 to prevent repetition of stock flagStartOver = True elif df_calc.loc[index, 'action'] == 'FatalError': df_calc.at[index, 'skip'] = 1 #df_calc.at[index,'action']='StockSelect' else: if df_calc.loc[index, 'ltp'] > 0.1: df_calc.at[index, 'pBase'] = df_calc.loc[index, 'ltp'] df_calc.at[index, 'action'] = 'BaseSet' counterStockTick += 1 else: if counterStockTick > 100: df_calc.at[index, 'action'] = 'BaseSet' else: df_calc.at[index, 'action'] = 'Waiting' #if all action status is the same -- steps for global changes if df_calc.action.nunique() == 1: if 'StockSelect' in df_calc.values: #filter out stocks df_calc = df_calc[df_calc.skip == 0] df_calc = df_calc[df_calc.buy > 10] df_calc = df_calc[df_calc.sell > 10] df_calc = df_calc[df_calc.high > 10] df_calc = df_calc[df_calc.low > 10] df_calc = df_calc[df_calc.ltp < 1000] df_calc = df_calc[df_calc.x > 1] #calculate volatility and rank if direction_switch == True: df_calc['v'] = df_calc['sell'] / df_calc['buy'] df_calc['v2'] = (df_calc['ltp'] - df_calc['low']) / ( df_calc['high'] - df_calc['low']) else: df_calc['v'] = df_calc['buy'] / df_calc['sell'] df_calc['v2'] = (df_calc['high'] - df_calc['ltp']) / ( df_calc['high'] - df_calc['low']) df_calc = df_calc[df_calc.v2 > 0.5] df_calc['rank'] = df_calc['v'].rank(ascending=False) df_calc['rank2'] = df_calc['v2'].rank(ascending=False) elif 'BaseSet' in df_calc.values: #set values to prevent error df_calc.loc[df_calc['sell'] == 0, 'sell'] += 1 df_calc.loc[df_calc['buy'] == 0, 'buy'] += 1 #t = timer() if flagMargin == False: if 12.5 in df_calc.values: pass else: getMarginX(df_calc) df_original = df_original.set_index('instrument_token') df_original = df_calc df_original = df_original.reset_index() flagMargin = True df_calc['action'] = 'StockSelect' df_calc = df_calc.reset_index() df = df_calc if flagStartOver == True: counterStockTick = 0 df = df_original flagStartOver = False os.system("cls") #pd.set_option('display.max_rows', len(df_calc)) if direction_switch == True: print('Direction: Sell -> Buy') else: print('Direction: Buy -> Sell') print(f'Stock count: {df.shape[0]}') print(df.nsmallest(5, 'rank')) if qDB.qsize() == 1: qDB.get() #pDB = Process(target=jobUpdateDB, args=(df_calc,qDB,1)) #pDB.start() #else: #logging.info('dataframe updated on RAM only, skipping DB write') #q.put(df_calc) time.sleep(.2)
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 on_ticks(ws, ticks): # Callback to receive ticks. logging.debug("Ticks: {}".format(ticks)) def on_connect(ws, response): # Callback on successful connect. # Subscribe to a list of instrument_tokens (RELIANCE and ACC here). ws.subscribe([738561, 5633]) # Set RELIANCE to tick in `full` mode. ws.set_mode(ws.MODE_FULL, [738561]) def on_close(ws, code, reason): # On connection close stop the main loop # Reconnection will not happen after executing `ws.stop()` ws.stop() # Assign the callbacks. kws.on_ticks = on_ticks kws.on_connect = on_connect kws.on_close = on_close # 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 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()