ERROR:kiteconnect.ticker:Connection closed: 1006 - connection was closed uncleanly (None)

Pranjal_K edited November 12 in Python client
I'm facing the above-mentioned error. The code runs for 5-10 mins, but then automatically starts printing this error. I have gone through the documentation and the forum links but can't seem to find the root cause. Please let me know what more information I can provide. Any help would be greatly appreciated :smile:

Here's my code snippet:

import numpy as np
from NSE_parser import getScripts
from Stocks import Stocks
import logging
from kiteconnect import KiteConnect
from kiteconnect import KiteTicker
import datetime
import pandas as pd


totalRisk = 1000
riskPerStock = totalRisk/4

# logging.basicConfig(level=logging.DEBUG)
apiKey = ""

kite = KiteConnect(api_key=apiKey)

print("Please input the correct tokens")
requestToken = input()

apiSecret = ""
data = kite.generate_session(requestToken, api_secret=apiSecret)

kws = KiteTicker(apiKey, data["access_token"])

NSE_data = np.array(df.values)
NSE_data = NSE_data[:, [0 ,2]]
NSE_dict = {b : a for a,b in NSE_data}

def createToken(scripts):
instrument_token = []
for script in scripts:
return instrument_token

def createStocks(scripts):
stocks = {}
instrument_token = createToken(scripts)
index = 0
for script in scripts:
stocks[instrument_token[index]] = Stocks(script, instrument_token[index])

return stocks

scripts = getScripts()
cur_Stocks = createStocks(scripts)
# print(cur_Stocks)

initTime_Level = datetime.datetime(1, 1, 1,12, 42, 0)
nextTime_Level = datetime.datetime(1, 1, 1,12, 44, 0)

def checkData(ws, time, price, token_Arr):
global totalRisk, initTime_Level, nextTime_Level, cur_Stocks, riskPerStock, initFlag
# print(time.time(), time.time() < initTime_Level.time())
if time.time() < initTime_Level.time(): #before 9:20
index = 0;
for token in token_Arr:
stocks = cur_Stocks[token]

elif time.hour == initTime_Level.hour and time.minute == initTime_Level.minute: #at 9:20
tradeAble_Flags = np.ones((len(cur_Stocks), 1))
index = 0
for token in token_Arr:
stocks = cur_Stocks[token]
if(stocks.setAndCheck_InitLevels() == 0):
print("unsubscribing => INITIAL RANGE", stocks.symbol_Name)
del cur_Stocks[token]

riskPerStock = totalRisk/len(cur_Stocks)

elif time.hour == nextTime_Level.hour and time.minute == nextTime_Level.minute: #after 9:20
index = 0
for token in token_Arr:
stocks = cur_Stocks[token]
if stocks.checkEntry(price[index]):
stocks.Enter(kite, riskPerStock)
index = 0

elif time.time() > nextTime_Level.time():
nextTime_Level = nextTime_Level + datetime.timedelta(minutes = 2)
print("DATE TIME MODIFIED", nextTime_Level.time())

for token in token_Arr:
stocks = cur_Stocks[token]
if stocks.CheckOrders(kite):
print("unsubscribing => ORDER complete", stocks.symbol_Name)
del cur_Stocks[token]


def on_ticks(ws, ticks):
# Callback to receive ticks.
logging.debug("Ticks: {}".format(ticks))
# cur_time = ticks[0]['last_trade_time']
# price_unordered =[script_dict['last_price'] for script_dict in ticks] #get price of all subscribed stocks
# token =[script_dict['instrument_token'] for script_dict in ticks]
# # price = redorder(price_unordered, token)
# # print(time, price)
# checkData(ws, cur_time, price_unordered, token)
# # if len(cur_Stocks.values()) == 0 or cur_time.time() > datetime(1, 1, 1, 15, 0, 0).time():
# # ws.stop()

def on_connect(ws, response):
# Callback on successful connect.
# Subscribe to a list of instrument_tokens (RELIANCE and ACC here).
instrument_token = []
print("Starting Connection")
for stocks in list(cur_Stocks.values()):
print("Subscription successful")
# Set RELIANCE to tick in `full` mode.
ws.set_mode(ws.MODE_FULL, instrument_token)
print("Connection successful", instrument_token)

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()

while True:
#Perform required data operation using tick data
def on_ticks(ws, ticks):
cur_time = ticks[0]['last_trade_time']
price_unordered =[script_dict['last_price'] for script_dict in ticks] #get price of all subscribed stocks
token =[script_dict['instrument_token'] for script_dict in ticks]
# price = redorder(price_unordered, token)
# print(time, price)
checkData(ws, cur_time, price_unordered, token)

ScreenShot of the error:

  • rakeshr
    Go through python WebSocket streaming FAQs here.
  • Pranjal_K
    I have already implemented the 'threaded=True' functionality mentioned in the FAQs for the 1006 error. I have created the subsequent while loops.
    Is there anything that I'm missing?
  • Pranjal_K
    Pranjal_K edited November 12
    Is this because I'm declaring some of my helper functions outside the while loop?
    I don't think that should be a problem, based on my understanding of the language.

    Also, there are no tab/indentation-related errors in the code. The indents are being removed here automatically. If attaching my code file would give more clarity, please let me know and I'll do that
Sign In or Register to comment.