Take a look

Tech

Live streaming real-time stock/options data using KiteConnect.

About KiteConnect –

Kiteconnect is a set of REST-like APIs that expose many capabilities required to build a complete investment and trading platform. Execute orders in real time, manage user portfolio, stream live market data (WebSockets), and more, with the simple HTTP API collection

This module provides an easy to use abstraction over the HTTP APIs. The HTTP calls have been converted to methods and their JSON responses are returned as native Python structures, for example, dicts, lists, bools etc.

For streaming any of the stock or options data we need the token corresponding to that stock/option. for eg. the token for HDFC is 340481, the token for Reliance is 738561. For getting the token of any instrument in kite, just open the chart and you will find it in the URL.

Find the below code which will stream the live data during market hours for HDFC and Reliance.

import time
import logging
from kiteconnect import KiteTicker, KiteConnect

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

# Initialise.
kws = KiteTicker(api_key, access_token)

tokens = [340481,738561]


# Callback for tick reception.
def on_ticks(ws, ticks):
    if len(ticks) > 0:
        logging.info("Current mode: {}".format(ticks[0]["mode"]))
    for tick in ticks:
        print(tick)
        
# Callback for successful connection.
def on_connect(ws, response):
    logging.info("Successfully connected. Response: {}".format(response))
    # ws.subscribe(tokens)
    ws.subscribe(tokens)
    # ws.set_mode(ws.MODE_FULL, tokens)
    logging.info("Subscribe to tokens in Full mode: {}".format(tokens))


# Callback when current connection is closed.
def on_close(ws, code, reason):
    logging.info("Connection closed: {code} - {reason}".format(code=code, reason=reason))


# Callback when connection closed with error.
def on_error(ws, code, reason):
    logging.info("Connection error: {code} - {reason}".format(code=code, reason=reason))


# Callback when reconnect is on progress
def on_reconnect(ws, attempts_count):
    logging.info("Reconnecting: {}".format(attempts_count))


# Callback when all reconnect failed (exhausted max retries)
def on_noreconnect(ws):
    logging.info("Reconnect failed.")


# Assign the callbacks.
kws.on_ticks = on_ticks
kws.on_close = on_close
kws.on_error = on_error
kws.on_connect = on_connect
kws.on_reconnect = on_reconnect
kws.on_noreconnect = on_noreconnect

# Infinite loop on the main thread.
# You have to use the pre-defined callbacks to manage subscriptions.
kws.connect(threaded=True)

# Block main thread
logging.info("This is main thread. Will change webosocket mode every 5 seconds.")

count = 0
while True:
    count += 1
    if count % 2 == 0:
        if kws.is_connected():
            logging.info("### Set mode to LTP for all tokens")
            kws.set_mode(kws.MODE_LTP, tokens)
    else:
        if kws.is_connected():
            logging.info("### Set mode to quote for all tokens")
            kws.set_mode(kws.MODE_FULL, tokens)

    time.sleep(5)

Callbacks

In below examples ws is the currently initialised WebSocket object.

  • on_ticks(ws, ticks) – Triggered when ticks are recevied.
    • ticks – List of tick object. Check below for sample structure.
  • on_close(ws, code, reason) – Triggered when connection is closed.
    • code – WebSocket standard close event code (https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent)
    • reason – DOMString indicating the reason the server closed the connection
  • on_error(ws, code, reason) – Triggered when connection is closed with an error.
    • code – WebSocket standard close event code (https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent)
    • reason – DOMString indicating the reason the server closed the connection
  • on_connect – Triggered when connection is established successfully.
    • response – Response received from server on successful connection.
  • on_reconnect(ws, attempts_count) – Triggered when auto reconnection is attempted.
    • attempts_count – Current reconnect attempt number.
  • on_noreconnect(ws) – Triggered when number of auto reconnection attempts exceeds reconnect_tries..

For more information read https://kite.trade/docs/pykiteconnect/v3/#kiteconnect.KiteTicker

The last part of just switches the mode every five seconds, you can use it in case your application needs data with market depth.

There are three different modes in which quote packets are streamed.

Leave a Reply