[Python] Zerodha API connection issue

Discussão em 'Python' iniciado por Stack, Abril 21, 2025.

  1. Stack

    Stack Membro Participativo

    I have designed a system that connects zerodha api that can automatically place orders on a specific time entered by the user. For example if a user want to place an order at 9:15:00 am, the user can set the trade early and system will automatically execute trade at 9:15:00 am. The code is running but order is not placed. The system is showing failed to connect, even though the api credentials are correct. Please help.....

    Here is the code.....

    import tkinter as tk
    from tkinter import ttk, messagebox
    from kiteconnect import KiteConnect
    import datetime
    import logging
    import pandas as pd
    import time

    # Set up logging
    logging.basicConfig(level=logging.INFO, filename='trading_log.log')

    # Initialize KiteConnect with your API credentials
    api_key = "YOUR_API_KEY" # Replace with your actual API key
    api_secret = "YOUR_API_SECRET" # Replace with your actual API secret
    access_token = "YOUR_ACCESS_TOKEN" # Replace with your actual access token

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

    def get_current_ist_time():
    """Get current time in IST (offset-aware)"""
    return datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=5, minutes=30)))

    def calculate_stop_loss_target(price, is_buy=True):
    """Calculate stop-loss (0.3%) and target (0.6%) based on entry price"""
    if is_buy:
    stop_loss = price * (1 - 0.003) # 0.3% below buy price
    target = price * (1 + 0.006) # 0.6% above buy price
    else: # Sell order
    stop_loss = price * (1 + 0.003) # 0.3% above sell price
    target = price * (1 - 0.006) # 0.6% below sell price
    return stop_loss, target

    def wait_until_target_time(target_time_str):
    """Wait until the target time is reached"""
    target_time = datetime.datetime.strptime(target_time_str, "%H:%M:%S").time()
    current_date = get_current_ist_time().date()
    target_datetime = datetime.datetime.combine(current_date, target_time).replace(tzinfo=datetime.timezone(datetime.timedelta(hours=5, minutes=30)))

    while True:
    current_datetime = get_current_ist_time()
    if current_datetime.time() >= target_time and 9 <= current_datetime.hour < 15: # Market hours
    logging.info(f"Reached target time {target_time_str}. Placing order...")
    return True
    else:
    wait_time = (target_datetime.replace(tzinfo=None) - current_datetime.replace(tzinfo=None)).total_seconds()
    if wait_time > 0:
    logging.info(f"Waiting {wait_time} seconds until {target_time_str}...")
    time.sleep(min(wait_time, 60))
    else:
    logging.info("Market hours not active or time passed. Exiting...")
    return False

    def place_order(stock_symbol, quantity, order_type="MARKET", price=None, transaction_type="BUY"):
    """Place a buy or sell order for the specified stock"""
    try:
    # Fetch instruments and validate stock symbol
    instruments = kite.instruments("NSE")
    instrument = next((item for item in instruments if item["tradingsymbol"] == stock_symbol), None)
    if not instrument:
    error_msg = f"Invalid stock symbol: {stock_symbol}"
    logging.error(error_msg)
    messagebox.showerror("Order Failed", error_msg)
    return None, None

    instrument_token = instrument["instrument_token"]
    logging.info(f"Placing {transaction_type} order for {stock_symbol}, Quantity: {quantity}, Order Type: {order_type}")

    # Place the order
    order_id = kite.place_order(variety=kite.VARIETY_REGULAR,
    exchange=kite.EXCHANGE_NSE,
    tradingsymbol=stock_symbol,
    transaction_type=kite.TRANSACTION_TYPE_BUY if transaction_type == "BUY" else kite.TRANSACTION_TYPE_SELL,
    quantity=quantity,
    order_type=order_type,
    price=price,
    product=kite.PRODUCT_CNC)

    logging.info(f"{transaction_type} order placed successfully for {stock_symbol}. Order ID: {order_id}")
    return order_id, instrument_token

    except Exception as e:
    error_msg = f"Error placing {transaction_type} order for {stock_symbol}: {str(e)}"
    logging.error(error_msg)
    messagebox.showerror("Order Failed", error_msg)
    return None, None

    class TradingApp:
    def __init__(self, root):
    self.root = root
    self.root.title("Zerodha Trading System")
    self.root.geometry("800x600")

    # Style the UI
    self.root.configure(bg='#f0f0f0')

    # Data storage for multiple stocks
    self.stocks = []

    # Create GUI elements
    self.create_widgets()

    def create_widgets(self):
    # Title
    title_label = tk.Label(self.root, text="Zerodha Automated Trading", font=("Arial", 16, "bold"), bg='#f0f0f0')
    title_label.pack(pady=10)

    # Frame for input
    input_frame = ttk.Frame(self.root, padding="10")
    input_frame.pack(fill="x", padx=10, pady=5)

    # Stock Symbol
    tk.Label(input_frame, text="Stock Symbol (e.g., INFY):").grid(row=0, column=0, padx=5, pady=5)
    self.stock_entry = tk.Entry(input_frame)
    self.stock_entry.grid(row=0, column=1, padx=5, pady=5)

    # Target Time
    tk.Label(input_frame, text="Target Time (HH:MM:SS):").grid(row=1, column=0, padx=5, pady=5)
    self.time_entry = tk.Entry(input_frame)
    self.time_entry.grid(row=1, column=1, padx=5, pady=5)

    # Quantity
    tk.Label(input_frame, text="Quantity:").grid(row=2, column=0, padx=5, pady=5)
    self.quantity_entry = tk.Entry(input_frame)
    self.quantity_entry.grid(row=2, column=1, padx=5, pady=5)

    # Order Type (Buy/Sell)
    tk.Label(input_frame, text="Order Type:").grid(row=3, column=0, padx=5, pady=5)
    self.order_type = tk.StringVar(value="BUY")
    tk.Radiobutton(input_frame, text="Buy", variable=self.order_type, value="BUY").grid(row=3, column=1, sticky="w")
    tk.Radiobutton(input_frame, text="Sell", variable=self.order_type, value="SELL").grid(row=3, column=1, sticky="e")

    # Buttons Frame
    button_frame = ttk.Frame(input_frame)
    button_frame.grid(row=4, column=0, columnspan=2, pady=10)

    # Add Stock Button
    add_button = tk.Button(button_frame, text="Add Stock", command=self.add_stock, bg='#4CAF50', fg='white')
    add_button.pack(side="left", padx=5)

    # Delete Stock Button
    delete_button = tk.Button(button_frame, text="Delete Selected Stock", command=self.delete_stock, bg='#f44336', fg='white')
    delete_button.pack(side="left", padx=5)

    # Treeview for displaying stocks
    self.tree = ttk.Treeview(self.root, columns=("Symbol", "Time", "Quantity", "Type", "Status"), show="headings", height=10)
    self.tree.heading("Symbol", text="Stock Symbol")
    self.tree.heading("Time", text="Target Time")
    self.tree.heading("Quantity", text="Quantity")
    self.tree.heading("Type", text="Order Type")
    self.tree.heading("Status", text="Status")
    for col in self.tree["columns"]:
    self.tree.column(col, width=100)
    self.tree.pack(fill="both", expand=True, padx=10, pady=10)

    # Start Trading Button
    start_button = tk.Button(self.root, text="Start Trading", command=self.start_trading, bg='#2196F3', fg='white')
    start_button.pack(pady=10)

    def add_stock(self):
    """Add a stock to the list"""
    stock_symbol = self.stock_entry.get().upper()
    target_time = self.time_entry.get()
    quantity = int(self.quantity_entry.get())
    order_type = self.order_type.get()

    if not all([stock_symbol, target_time, quantity]):
    messagebox.showerror("Error", "Please fill all fields!")
    return

    try:
    self.stocks.append({"symbol": stock_symbol, "time": target_time, "quantity": quantity, "type": order_type})
    self.tree.insert("", "end", values=(stock_symbol, target_time, quantity, order_type, "Pending"))
    self.clear_entries()
    except ValueError:
    messagebox.showerror("Error", "Invalid input! Check quantity.")

    def clear_entries(self):
    """Clear input fields"""
    self.stock_entry.delete(0, tk.END)
    self.time_entry.delete(0, tk.END)
    self.quantity_entry.delete(0, tk.END)

    def delete_stock(self):
    """Delete the selected stock from the list and Treeview"""
    selected_item = self.tree.selection()
    if not selected_item:
    messagebox.showwarning("Warning", "Please select a stock to delete!")
    return

    values = self.tree.item(selected_item[0], "values")
    stock_symbol = values[0]
    self.stocks = [stock for stock in self.stocks if stock["symbol"] != stock_symbol]
    self.tree.delete(selected_item)
    messagebox.showinfo("Success", f"Stock {stock_symbol} has been deleted.")

    def start_trading(self):
    """Start placing orders at target times"""
    for stock in self.stocks:
    if wait_until_target_time(stock["time"]):
    order_id, instrument_token = place_order(stock["symbol"], stock["quantity"], transaction_type=stock["type"])
    if order_id:
    try:
    quote = kite.quote("NSE:" + stock["symbol"])
    current_price = quote["NSE:" + stock["symbol"]]["last_price"]

    stop_loss, target = calculate_stop_loss_target(current_price, stock["type"] == "BUY")

    for item in self.tree.get_children():
    values = self.tree.item(item, "values")
    if values[0] == stock["symbol"]:
    self.tree.item(item, values=(values[0], values[1], values[2], values[3], f"Executed - SL: {stop_loss:.2f}, Target: {target:.2f}"))

    logging.info(f"Order executed for {stock['symbol']}. Stop Loss: {stop_loss}, Target: {target}")
    except Exception as e:
    logging.error(f"Error fetching quote for {stock['symbol']}: {str(e)}")
    messagebox.showerror("Quote Error", f"Failed to fetch quote for {stock['symbol']}: {str(e)}")
    else:
    for item in self.tree.get_children():
    values = self.tree.item(item, "values")
    if values[0] == stock["symbol"]:
    self.tree.item(item, values=(values[0], values[1], values[2], values[3], "Failed"))
    else:
    for item in self.tree.get_children():
    values = self.tree.item(item, "values")
    if values[0] == stock["symbol"]:
    self.tree.item(item, values=(values[0], values[1], values[2], values[3], "Time Expired"))

    if __name__ == "__main__":
    root = tk.Tk()
    app = TradingApp(root)
    root.mainloop()

    Continue reading...

Compartilhe esta Página