Too many errors could not connect to websocket

aravindchandrajohn
Hey I'm trying to get live market data and only purpose of subscribing api is to get live data into python for back testing . But below is my code I created with the help of AI and I'm totally beginner to this kindly help

import sqlite3
import threading
import time
from kiteconnect import KiteConnect, KiteTicker
from datetime import datetime
import logging

# Constants
API_KEY = ''
ACCESS_TOKEN = ''
DB_NAME = 'market_data.db'
RATE_LIMIT_DELAY = 1 # Delay in seconds between API requests

# Define Nifty 50 and Nifty Midcap 500 symbols
NIFTY_50_SYMBOLS = [
"ADANIPORTS", "ASIANPAINT", "AXISBANK", "BAJAJ-AUTO", "BAJFINANCE",
"BAJAJFINSV", "BPCL", "BHARTIARTL", "BRITANNIA", "CIPLA",
"COALINDIA", "DIVISLAB", "DRREDDY", "EICHERMOT", "GRASIM",
"HCLTECH", "HDFCBANK", "HDFCLIFE", "HEROMOTOCO", "HINDALCO",
"HINDUNILVR", "ICICIBANK", "INDUSINDBK", "INFY", "IOC",
"ITC", "JSWSTEEL", "KOTAKBANK", "LT", "M&M",
"MARUTI", "NESTLEIND", "NTPC", "ONGC", "POWERGRID",
"RELIANCE", "SBILIFE", "SHREECEM", "SBIN", "SUNPHARMA",
"TCS", "TATACONSUM", "TATAMOTORS", "TATASTEEL", "TECHM",
"TITAN", "ULTRACEMCO", "UPL", "WIPRO", "ZEEL"
]

NIFTY_MIDCAP_500_SYMBOLS = [
"ABB", "ACC", "AUBANK", "AARTIIND", "ADANIGREEN",
"ADANITRANS", "ALKEM", "AMARAJABAT", "APOLLOHOSP", "APOLLOTYRE",
"ASHOKLEY", "AUROPHARMA", "BANDHANBNK", "BANKBARODA", "BATAINDIA",
"BERGEPAINT", "BHARATFORG", "BIOCON", "BOSCHLTD", "CADILAHC",
"CANBK", "CHOLAFIN", "CUB", "DABUR", "DHANI",
"DLF", "DALBHARAT", "EDELWEISS", "EIHOTEL", "ESCORTS",
"EXIDEIND", "FEDERALBNK", "GAIL", "GLENMARK", "GODREJCP",
"GODREJPROP", "GRANULES", "HAVELLS", "HDFCAMC", "HINDPETRO",
"IDFCFIRSTB", "IGL", "INDHOTEL", "INDIAMART", "INDIGO",
"IPCALAB", "JINDALSTEL", "JUBLFOOD", "L&TFH", "LICHSGFIN",
"LTI", "LTTS", "MANAPPURAM", "MARICO", "MFSL",
"MINDTREE", "MOTHERSUMI", "MPHASIS", "MRF", "MUTHOOTFIN",
"NAM-INDIA", "NATCOPHARM", "NAUKRI", "NAVINFLUOR", "NMDC",
"OBEROIRLTY", "OFSS", "PAGEIND", "PEL", "PETRONET",
"PFC", "PIDILITIND", "PNB", "PVR", "RAMCOCEM",
"RBLBANK", "RECLTD", "SAIL", "SIEMENS", "SRF",
"SRTRANSFIN", "STAR", "SUNTV", "SYNGENE", "TATACHEM",
"TATACOMM", "TATAPOWER", "TVSMOTOR", "UBL", "VBL",
"VEDL", "VOLTAS", "WHIRLPOOL", "YESBANK", "ZEEL"
]

# Initialize KiteConnect
kite = KiteConnect(api_key=API_KEY)
kite.set_access_token(ACCESS_TOKEN)

# SQLite database setup
def init_db():
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS market_data (
instrument_token INTEGER,
tradingsymbol TEXT,
last_price REAL,
ohlc_open REAL,
ohlc_high REAL,
ohlc_low REAL,
ohlc_close REAL,
volume INTEGER,
timestamp TEXT
)''')
conn.commit()
conn.close()

# Fetch instrument tokens for Nifty 50 and Nifty Midcap 500
def fetch_instrument_tokens():
instruments = kite.instruments()
nifty_50_tokens = [instrument['instrument_token'] for instrument in instruments if instrument['tradingsymbol'] in NIFTY_50_SYMBOLS]
nifty_midcap_500_tokens = [instrument['instrument_token'] for instrument in instruments if instrument['tradingsymbol'] in NIFTY_MIDCAP_500_SYMBOLS]
return nifty_50_tokens + nifty_midcap_500_tokens

# WebSocket on_ticks callback
def on_ticks(ws, ticks):
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
for tick in ticks:
cursor.execute('''INSERT INTO market_data (instrument_token, tradingsymbol, last_price, ohlc_open, ohlc_high, ohlc_low, ohlc_close, volume, timestamp)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)''',
(tick['instrument_token'], tick['tradingsymbol'], tick['last_price'], tick['ohlc']['open'], tick['ohlc']['high'], tick['ohlc']['low'], tick['ohlc']['close'], tick['volume'], datetime.now()))
conn.commit()
conn.close()

# WebSocket on_connect callback
def on_connect(ws, response):
ws.subscribe(tokens)
ws.set_mode(ws.MODE_FULL, tokens)

# WebSocket on_close callback
def on_close(ws, code, reason):
print(f"Connection closed: {code} - {reason}")
# Reconnect logic
time.sleep(5)
start_websocket()

# Start WebSocket connection
def start_websocket():
kws = KiteTicker(API_KEY, ACCESS_TOKEN)
kws.on_ticks = on_ticks
kws.on_connect = on_connect
kws.on_close = on_close
kws.connect(threaded=True)

# Main function
if __name__ == "__main__":
init_db()
tokens = fetch_instrument_tokens()
start_websocket()
Sign In or Register to comment.