i activated zerodha api key

TIW057
from kiteconnect import KiteConnect, KiteTicker
import pandas as pd
import openpyxl
import time

# Zerodha API Credentials
api_key = "pgjrqpjbf23a2lq4"
access_token = "YOUR_ACCESS_TOKEN" # <<< Paste your access token here

kite = KiteConnect(api_key=api_key)
kite.set_access_token(access_token)

# NIFTY 50 stock list
nifty50_stocks = [
"ADANIPORTS", "ASIANPAINT", "AXISBANK", "BAJAJ-AUTO", "BAJFINANCE",
"BAJAJFINSV", "BHARTIARTL", "BPCL", "BRITANNIA", "CIPLA",
"COALINDIA", "DIVISLAB", "DRREDDY", "EICHERMOT", "GRASIM",
"HCLTECH", "HDFCBANK", "HDFCLIFE", "HEROMOTOCO", "HINDALCO",
"HINDUNILVR", "ICICIBANK", "ITC", "INDUSINDBK", "INFY",
"JSWSTEEL", "KOTAKBANK", "LT", "M&M", "MARUTI",
"NESTLEIND", "NTPC", "ONGC", "POWERGRID", "RELIANCE",
"SBILIFE", "SBIN", "SUNPHARMA", "TATAMOTORS", "TATASTEEL",
"TCS", "TECHM", "TITAN", "ULTRACEMCO", "UPL",
"WIPRO"
]

# Prepare token mapping
instrument_dump = kite.instruments("NSE")
token_map = {item['tradingsymbol']: item['instrument_token'] for item in instrument_dump if item['tradingsymbol'] in nifty50_stocks}

# File to save
excel_filename = "nifty50_live_ticks.xlsx"

# Initialize Excel
def initialize_excel():
df = pd.DataFrame(nifty50_stocks, columns=["Stock"])
df["LTP"] = 0.0
df.to_excel(excel_filename, index=False)
print(f"Excel file '{excel_filename}' initialized.")

initialize_excel()

live_data = {}

# Zerodha Ticker Connection
kws = KiteTicker(api_key, access_token)

def on_ticks(ws, ticks):
global live_data
for tick in ticks:
instrument_token = tick['instrument_token']
for tradingsymbol, token in token_map.items():
if token == instrument_token:
last_price = tick['last_price']
live_data[tradingsymbol] = last_price

# Save live data to Excel
if live_data:
df = pd.DataFrame(list(live_data.items()), columns=["Stock", "LTP"])
df = df.sort_values("Stock")
df.to_excel(excel_filename, index=False)
print("Excel updated at", time.strftime("%H:%M:%S"))

def on_connect(ws, response):
print("Connected to Zerodha Websocket!")
tokens = list(token_map.values())
ws.subscribe(tokens)
ws.set_mode(ws.MODE_LTP, tokens)

def on_close(ws, code, reason):
print("Connection closed:", code, reason)

kws.on_ticks = on_ticks
kws.on_connect = on_connect
kws.on_close = on_close

# Connect
kws.connect(threaded=True)

# Keep running forever
while True:
time.sleep(1)
Sign In or Register to comment.