コード例 #1
0
ファイル: tick_data.py プロジェクト: yudhv/PyTrading
def tick_init(api_key, public_token, id):
	kws = WebSocket(api_key, public_token, id)
	make_tick_df()
	#Remove below line before restarting in order to save data
	make_tick_file()
	num = int(input("Enter the number of stocks to subscribe\n"))
	set_subscription_list(num)
	# Assign the callbacks.
	kws.on_tick = on_tick
	kws.on_connect = on_connect

	# Infinite loop on the main thread. Nothing after this will run.
	# You have to use the pre-defined callbacks to manage subscriptions.
	kws.connect(True)
コード例 #2
0
ファイル: ATR_NEW.py プロジェクト: ajmal017/AutoTradeRunner
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)
コード例 #3
0
kite_api_key = "yw8yelu5bpfel8ib"
kite_api_secret = "vaddqe1qb3lzorst3uolc1ptdo0l2cku"

kws = WebSocket(kite_api_key, 'Kf879HRiMNS0DbOREhO1KyDqRl3J2bWu', "YK8879")


def on_ticks(tick, ws):
    # Callback to receive ticks.
    #logging.debug("Ticks: {}".format(ticks))
    with open("2_4_2018_1", "a+") as f:
        f.write(str(tick))
    print(tick)


def on_connect(ws):
    # 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, 5633])


# Assign the callbacks.
kws.on_tick = on_ticks
kws.on_connect = on_connect

# Infinite loop on the main thread. Nothing after this will run.
# You have to use the pre-defined callbacks to manage subscriptions.
kws.connect()
コード例 #4
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)
コード例 #5
0
ファイル: ws.py プロジェクト: ansumanm/Projects
# 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()
コード例 #6
0
    logging.info("WebSocket connection closed")


def on_error():
    logging.info("WebSocket connection thrown error")


# Assign the callbacks.
kws.on_tick = on_tick
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(threaded=True)
# kws.connect(disable_ssl_verification=True) # for ubuntu

count = 0
while True:
    logging.info(
        "This is main thread. Will subscribe to each token in tokens list with 5s delay"
    )

    if count < len(tokens):
        if kws.is_connected():
            logging.info("Subscribing to: {}".format(tokens[count]))
            kws.subscribe([tokens[count]])
            kws.set_mode(kws.MODE_LTP, [tokens[count]])
            count += 1
        else:
コード例 #7
0
kite.set_access_token(rq['access_token'])

kite.ohlc("NSE:INFY")

#kite.set_access_token('xjsfx1mymtr3j340g2u4hhy1sshrtl6d')
kws = WebSocket(kite_api_key, 'Kf879HRiMNS0DbOREhO1KyDqRl3J2bWu', "YK8879")


def on_ticks(tick, ws):
    # Callback to receive ticks.
    #logging.debug("Ticks: {}".format(ticks))
    print(tick)


def on_connect(ws):
    # 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])


# Assign the callbacks.
kws.on_tick = on_ticks
kws.on_connect = on_connect

# Infinite loop on the main thread. Nothing after this will run.
# You have to use the pre-defined callbacks to manage subscriptions.
kws.connect(disable_ssl_verification=True, proxy=proxy)