Ejemplo n.º 1
0
class MarketData():
    instrument_list = list()
    #stock_price = dict()
    instr_to_stock = dict()

    def __init__(self, instruments, public_token):
        # Initialise.
        global mkt_data
        self.kws = WebSocket(config.api_key, public_token, config.kite_id)

        self.publish_file = config.BaseDir_W + "Data\\" + config.LiveDataFile
        self.instrument_list = list(instruments.values())
        # Assign the callbacks.
        self.kws.on_tick = self.on_tick
        self.kws.on_connect = self.on_connect

        self.kws.enable_reconnect(reconnect_interval=5, reconnect_tries=50)

        # Initialize all prices with 0. instr_to_stock = 12345:BHEL
        for key in instruments.keys():
            #self.stock_price[key] = 0.0
            mkt_data[key] = 0.0
            self.instr_to_stock[instruments[key]] = key

        # set time
        self.time_counter = time.time()

    def start(self):
        self.kws.connect(threaded=True)
        #self.kws.connect()

    def on_tick(self, tick, ws):
        global mkt_data

        for item in tick:
            #tick_list[item['instrument_token']] =  item['last_price']
            mkt_data[self.instr_to_stock[
                item['instrument_token']]] = item['last_price']

        print("Tick ------", time.strftime("%H:%M:%S"))

    def on_connect(self, ws):
        ws.subscribe(self.instrument_list)
Ejemplo n.º 2
0
class MarketData( ):
    instrument_list = list()
    stock_price = dict()
    instr_to_stock = dict()
     
    
    def __init__(self,instruments,session_id):
        # Initialise.
        self.kws = WebSocket(config.api_key , session_id, config.kite_id)
            
        self.publish_file = config.BaseDir_W + "Data\\" + config.LiveDataFile
        self.instrument_list = list(instruments.values() )
        # Assign the callbacks.
        self.kws.on_tick    = self.on_tick
        self.kws.on_connect = self.on_connect
        
        self.kws.enable_reconnect(reconnect_interval=5, reconnect_tries=50)
        
        # Initialize all prices with 0. instr_to_stock = 12345:BHEL
        for key in instruments.keys():
            self.stock_price[key] = 0.0
            self.instr_to_stock[instruments[key]] = key
            
        # set time 
        self.time_counter = time.time()
        
    def start(self):
        #self.kws.connect(threaded=True)
        self.kws.connect()
        
    def on_tick(self,tick, ws):   
        tick_list = dict()
        
        # get all data in dict tick_list = 12345:145.0
        for item in tick:
            tick_list[item['instrument_token']] =  item['last_price']
        
        #print("Tick ",time.time(), tick_list)
        print("Tick ---- ",time.strftime("%H:%M:%S") )
        
        # update stock price in dict
        for key,value in tick_list.items():
            stk = self.instr_to_stock[key]  # get stock name   
            self.stock_price[stk] = value# create dict = {'BHEL': 125.65, 'WIPRO': 290.25 }
        print("stock_price dic done---- ",time.strftime("%H:%M:%S") )
        # set data in environment variable                        
        var_string = ""
        for stock,price in self.stock_price.items():
             var_string += stock + ":" + str(price) + ','   
        print("var_string formed---- ",time.strftime("%H:%M:%S") )
        # write file every x minutes
        if time.time() - self.time_counter  >= config.MarketData_Write_Interval:
            try:
                timestart = time.time()
                with open(self.publish_file, 'w') as f:
                    f.write("TimeStamp:" + time.strftime("%Y%m%d%H%M%S") + ',' +  var_string[:-1])
                    print(time.strftime("%H:%M:%S"), var_string[:-1])
                self.time_counter = time.time()
                print("TIMETAKEN: ",time.time()-timestart)
            except Exception as e:
                print("Market data write in file error. ")
                exit()
        
        
    def on_connect(self,ws):        
        ws.subscribe(self.instrument_list)
Ejemplo n.º 3
0
# Assign the callbacks.
kws.on_tick = on_tick
kws.on_connect = on_connect

# To enable auto reconnect WebSocket connection in
# case of network failure
# - First param is interval between reconnection
# attempts in seconds.
# Callback `on_reconnect` is triggered on every
# reconnection attempt. (Default interval is 5
# seconds)
# - Second param is maximum number of retries before
# the program exits triggering `on_noreconnect`
# calback. (Defaults to 50 attempts)
# Note that you can also enable auto reconnection
# while initialising websocket.
# Example `kws = WebSocket("your_api_key",
# "your_public_token", "logged_in_user_id",
# reconnect=True, reconnect_interval=5,
# reconnect_tries=50)`
kws.enable_reconnect(reconnect_interval=5, reconnect_tries=50)

# Infinite loop on the main thread. Nothing after
# this will run.
# You have to use the pre-defined callbacks to
# manage subscriptions.
print("""
        Trying to connect...
        """)
kws.connect()