pykiteconnect

repository·master·Indexed 23 days ago

https://github.com/zerodha/pykiteconnect

The official Python client for the Kite Connect API. It enables developers to build investment and trading platforms featuring real-time order execution, portfolio management, and live market data streaming via WebSockets using KiteTicker.

Tokens
1.9K
Snippets
5
Records
6
Agent score
30%

What's inside pykiteconnect

  1. Authenticate and initialize KiteConnect

    master

    To use the API, you must first obtain a request_token via the login URL provided by kite.login_url(). Once you receive the request_token from your registered redirect URL, use generate_session to obtain an access_token. Finally, set the access token on your KiteConnect instance.

    from kiteconnect import KiteConnect
    
    kite = KiteConnect(api_key="your_api_key")
    
    # After receiving request_token from the redirect URL
    data = kite.generate_session("request_token_here", api_secret="your_secret")
    kite.set_access_token(data["access_token"])
  2. Configure C compilers for installation

    master

    If you encounter errors during installation due to C extensions, ensure you have the appropriate compiler for your operating system:

    Linux, BSD and macOS

    • Debian/Ubuntu: apt-get install libffi-dev python-dev python3-dev
    • Centos/RHEL/Fedora: yum install libffi-devel python3-devel python-devel
    • macOS/OSx: xcode-select --install

    Microsoft Windows

    Install the Microsoft Visual C++ version that corresponds to your Python version:

    • Python 2.6 - 3.2: Visual C++ 9.0
    • Python 3.3 - 3.4: Visual C++ 10.0
    • Python 3.5 - 3.6: Visual C++ 14.0
  3. Install the Kite Connect Python client

    master

    Install the client using pip. It is recommended to update pip and setuptools first to avoid installation issues.

    Note: Some dependencies use C extensions and require a C compiler to be installed on your system.

    pip install -U pip setuptools
    pip install --upgrade kiteconnect
  4. Stream live market data with KiteTicker (WebSocket)

    master

    Use KiteTicker to establish a WebSocket connection for real-time market data. You must define callbacks for on_ticks, on_connect, and on_close to handle data and connection lifecycle events.

    import logging
    from kiteconnect import KiteTicker
    
    logging.basicConfig(level=logging.DEBUG)
    
    # Initialise
    kws = KiteTicker("your_api_key", "your_access_token")
    
    def on_ticks(ws, ticks):
        # Callback to receive ticks.
        logging.debug("Ticks: {}".format(ticks))
    
    def on_connect(ws, response):
        # 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])
    
    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()
  5. Place orders and manage instruments

    master

    Use the KiteConnect instance to place various types of orders (Regular, AMO, Mutual Fund) and fetch market data like instruments and orders.

    import logging
    from kiteconnect import KiteConnect
    
    logging.basicConfig(level=logging.DEBUG)
    kite = KiteConnect(api_key="your_api_key")
    # ... authentication steps ...
    
    # Place an order
    try:
        order_id = kite.place_order(tradingsymbol="INFY",
                                    exchange=kite.EXCHANGE_NSE,
                                    transaction_type=kite.TRANSACTION_TYPE_BUY,
                                    quantity=1,
                                    variety=kite.VARIETY_AMO,
                                    order_type=kite.ORDER_TYPE_MARKET,
                                    product=kite.PRODUCT_CNC,
                                    validity=kite.VALIDITY_DAY)
        logging.info("Order placed. ID is: {}".format(order_id))
    except Exception as e:
        logging.info("Order placement failed: {}".format(e.message))
    
    # Fetch all orders
    kite.orders()
    
    # Get instruments
    kite.instruments()
    
    # Place a mutual fund order
    kite.place_mf_order(
        tradingsymbol="INF090I01239",
        transaction_type=kite.TRANSACTION_TYPE_BUY,
        amount=5000,
        tag="mytag"
    )
    
    # Cancel a mutual fund order
    kite.cancel_mf_order(order_id="order_id")
    
    # Get mutual fund instruments
    kite.mf_instruments()
  6. Place auto-sliced orders

    master

    Use place_autoslice_order() to place orders that exceed exchange freeze limits. The method automatically splits the order into smaller chunks. The response contains a parent order_id and a children list. Each child in the list is either a successful order_id or an error payload.

    response = kite.place_autoslice_order(
        variety=kite.VARIETY_REGULAR,
        exchange=kite.EXCHANGE_NFO,
        tradingsymbol="NIFTY25APRFUT",
        transaction_type=kite.TRANSACTION_TYPE_BUY,
        quantity=100000,
        product=kite.PRODUCT_MIS,
        order_type=kite.ORDER_TYPE_MARKET,
    )
    
    parent_order_id = response["order_id"]
    for child in response.get("children", []):
        if "order_id" in child:
            ...  # child placed
        else:
            ...  # child["error"] payload