def kite_ticker_handler(manager, msg): global kws, kite, kite_api_key, access_token pdebug('kite_ticker_handler: {}'.format(msg)) # 1: Start kite websocket connections # Initialise if kws is None and msg != 'INIT': return pdebug('kite_ticker_handler: Exec {}'.format(msg)) if msg == 'INIT': try: cache.set('KiteAPIKey',kite_api_key) access_token = cache.get('access_token') kite.set_access_token(access_token) pinfo(kite.access_token) kws = KiteTicker(kite_api_key, kite.access_token) # Assign the callbacks. kws.on_ticks = on_ticks kws.on_connect = on_connect kws.on_order_update = on_order_update #kws.on_close = on_close cache.publish('kite_ticker_handler'+cache_postfix,'START') except Exception as e: perror('Could not connect to KITE server: {}'.format(e)) elif msg == 'START': kws.connect(threaded=True) #kws.subscribe(value) #kws.set_mode(kws.MODE_LTP, value) #Default mode LTP elif msg == 'STATUS': pinfo(kws.is_connected()) elif msg == 'CLOSE': cache.set('Kite_Status','closed') cache.publish('ohlc_tick_handler'+cache_id,'stop') #cache.publish('ohlc_tick_handler'+cache_id,'stop') kws.close() elif msg == 'profile': pinfo(kite.profile()) else: try: msg_j = json.loads(msg) cmd = msg_j['cmd'] value = msg_j['value'] mode_map = {'ltp':kws.MODE_LTP, 'full':kws.MODE_FULL, 'quote': kws.MODE_QUOTE} mode = mode_map[msg_j['mode']] if cmd == 'add': kws.subscribe(value) kws.set_mode(mode, value) pinfo('Subscribe: {}: {}'.format(cmd, msg)) elif cmd == 'remove': kws.unsubscribe(value) pinfo('Un-Subscribe: {}: {}'.format(cmd, msg)) elif cmd == 'mode': pinfo('Set Mode: {}: {}'.format(cmd, msg)) kws.set_mode(mode, value) except: pass
def start_collecting(self): # Assign the callbacks. ticksdir = os.path.join(os.getcwd(), 'ticks') if not os.path.exists(ticksdir): os.makedirs(ticksdir) kwsone = KiteTicker(self.api_key, self.access_token) kwsone.on_ticks = self.on_tick() kwsone.on_connect = self.on_connect(self.stocklist) if self.postback: kwsone.on_order_update = self.on_order_update() kwsone.connect(threaded=True)
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)
# Initialise kws = KiteTicker(api_key, access_token) def on_ticks(ws, ticks): var.ticks = ticks t1.run() def on_connect(ws, response): # Callback on successful connect. ws.subscribe(symbol_tokens) ws.set_mode(ws.MODE_LTP, symbol_tokens) def on_order_update(ws, data): print('ORDER_UPDATE :', data['status_message']) def on_close(ws, code, reason): ws.stop() t1 = trade_sniffer() kws.on_ticks = on_ticks kws.on_connect = on_connect kws.on_order_update = on_order_update kws.on_close = on_close kws.connect()
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()
# Set tick in `full` mode. ws.set_mode(ws.MODE_FULL, instruments) #get data from yahoo website #tick_handler.get_prev_candles_data_from_yahoo() def on_order_update(ws, data): util.lgr_kite_web.log(util.levels[0],'in on_order_update') util.lgr_kite_web.log(util.levels[0],data) pdb.set_trace() kite_ws.on_ticks = on_ticks # Triggered when ticks are received. kite_ws.on_connect = on_connect # Triggered when connection is established successfully kite_ws.on_order_update = on_order_update # Triggered when there is an order update for the connected user # Infinite loop on the main thread. Nothing after this will run. # You have to use the pre-defined callbacks to manage subscriptions. kite_ws.connect(threaded=True) """ ticks_list = [ {"tradable": True, 'mode': 'full', 'instrument_token': 5633,'last_price': 1660.55, 'last_quantity': 4, 'average_price': 1656.29, 'volume': 1578664, 'buy_quantity': 0, 'sell_quantity': 306, 'ohlc': {'open': 1682.6, 'high': 1682.6, 'low': 1637.7, 'close': 1665.95}, 'change': -0.3241393799333768, 'last_trade_time': datetime.datetime(2020, 12, 7, 15, 44, 2), 'oi': 0, 'oi_day_high': 0, 'oi_day_low': 0, 'timestamp': datetime.datetime(2020, 12, 7, 17, 10, 10), 'depth': {'buy': [{'quantity': 0, 'price': 0.0, 'orders': 0}, {'quantity': 0, 'price': 0.0, 'orders': 0}, {'quantity': 0, 'price': 0.0, 'orders': 0}, {'quantity': 0, 'price': 0.0, 'orders': 0}, {'quantity': 0, 'price': 0.0, 'orders': 0}], 'sell': [{'quantity': 306, 'price': 1660.55, 'orders': 8}, {'quantity': 0, 'price': 0.0, 'orders': 0}, {'quantity': 0, 'price': 0.0, 'orders': 0}, {'quantity': 0, 'price': 0.0, 'orders': 0}, {'quantity': 0, 'price': 0.0, 'orders': 0}]}}, {"tradable": True, 'mode': 'full', 'instrument_token': 5633, 'last_price': 1660.55, 'last_quantity': 4, 'average_price': 1656.29, 'volume': 1578664, 'buy_quantity': 0, 'sell_quantity': 306, 'ohlc': {'open': 1682.6, 'high': 1682.6, 'low': 1637.7, 'close': 1665.95},
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()