WebSockets and Threading in Trading with Kite Connect API

WebSockets and threading are two powerful concepts that, when wielded effectively, can immensely enhance the efficiency and responsiveness of automated trading applications. Let’s dive deep into these concepts in the context of the Kite Connect API.

What are WebSockets?

WebSockets represent a communication protocol that establishes a persistent, two-way channel between a client and a server over a single, long-lived connection.

Unlike the conventional HTTP protocol, where communication is initiated by the client, and the server responds, WebSockets allow the server to push real-time updates actively to the client. 

This makes WebSockets particularly impactful in trading applications where having real-time market data is pivotal for making informed trading decisions.

WebSockets in Kite Connect API

				
					# Importing necessary modules for logging and KiteTicker
import logging
from kiteconnect import KiteTicker

# Setting the logging basic configuration to debug level
logging.basicConfig(level=logging.DEBUG)

# Creating an instance of KiteTicker with necessary credentials
kws = KiteTicker("yourapikey", "yourapisecret")

# Defining a function to handle new market data ("ticks") that the WebSocket receives
def on_ticks(ws, ticks):
    # Logging the received ticks at the debug level
    logging.debug(f"Ticks: {ticks}")

# Defining a function to handle the event when a WebSocket connection is established
def on_connect(ws, response):
    # Subscribing to a specific token to receive relevant market data
    ws.subscribe([256265])
    # Setting the mode to full to receive all data related to the subscribed token
    ws.set_mode(ws.MODE_FULL, [256265])

# Defining a function to handle the closing of a WebSocket connection
def on_close(ws, code, reason):
    # Stopping the WebSocket from listening to further messages
    ws.stop()

# Assigning the defined functions to handle corresponding WebSocket events
kws.on_ticks = on_ticks
kws.on_connect = on_connect
kws.on_close = on_close

# Establishing the WebSocket connection
kws.connect()

				
			

Kite Connect API leverages the power of WebSockets through its KiteTicker module. 

The KiteTicker WebSocket API is tailored to provide real-time market updates like order updates, live quotes, and more. It’s an essential tool for traders who rely on real-time data to make trading decisions, manage risk, or monitor their portfolio’s performance.

In the provided code snippet, the WebSocket connection is established using the KiteTicker class. Methods like on_ticks, on_connect, and on_close are defined to handle various WebSocket events:

  • on_ticks: Invoked when new market data (“ticks”) are received.
  • on_connect: Executed when the WebSocket connection is successfully established. It subscribes to specific tokens to receive relevant market data.
  • on_close: Called when the WebSocket connection is closed, ensuring that the WebSocket stops listening for new messages.

Threading

Threading is a technique that allows a program to execute multiple operations concurrently. 

In the context of trading applications, threading can be used to run the WebSocket listener in the background, ensuring that the main application remains responsive and capable of handling other tasks, like user inputs or calculations, concurrently.

WebSockets and Threading

When threading is applied to WebSockets in a trading application, it brings about a synergistic effect. 

The WebSocket continually listens for market updates in a separate thread, ensuring that the application is always in sync with the market’s latest state without blocking the main application flow. This allows for a more fluid and responsive trading application that can adapt in real-time as market conditions evolve.

				
					import threading
import logging
from kiteconnect import KiteTicker

class ThreadingData(object):

    global app_z_status, app_z_order, app_z_order_type, app_z_transaction_type

    # Initializing global variables
    app_z_status = []
    app_z_order = []
    app_z_order_type = []
    app_z_transaction_type = []

    def __init__(self):
        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True  # Daemonizing the thread
        thread.start()

    def run(self):

        # Your personal access token and API key
        access_token = "youraccess_token" 
        api_key = "yourapikey"
        
        logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        
        kws = KiteTicker(api_key, access_token, debug=True)

        # Tokens of the instruments you want to get data for
        tokens = [131169028]
        
        # Defining the functions for handling WebSocket events
        def on_connect(ws, response):
            ws.subscribe(tokens)
            ws.set_mode(ws.MODE_FULL, tokens)

        def on_order_update(ws, data):
            z_status = data['status']
            z_order = data["order_id"]
            z_order_type = data["order_type"]
            z_transaction_type = ["transaction_type"]
            
            # Storing the order updates in global variables
            app_z_status.append(z_status)
            app_z_order.append(z_order)
            app_z_order_type.append(z_order_type)
            app_z_transaction_type.append(z_transaction_type)
            
            # Printing the stored order updates
            print(app_z_status)
            print(app_z_order)
            print(app_z_order_type)
            print(app_z_transaction_type)
            print(data)
            
        # Assigning the functions to KiteTicker object
        kws.on_connect = on_connect
        kws.on_order_update = on_order_update

        # Connecting to the WebSocket
        kws.connect()

# Creating an instance of the ThreadingData class
thre = ThreadingData()

				
			

Output – 

				
					{'average_price': 0, 'cancelled_quantity': 0, 'disclosed_quantity': 0, 'exchange': 'NSE', 'exchange_order_id': None, 'exchange_timestamp': None, 'filled_quantity': 0, 'guid': '10778X8ZFO5b41UslC', 'instrument_token': 857857, 'market_protection': 0, 'order_id': '190521001155150', 'order_timestamp': datetime.datetime(2019, 5, 21, 10, 54, 46), 'order_type': 'SL', 'parent_order_id': None, 'pending_quantity': 0, 'placed_by': 'BQ8330', 'price': 555, 'product': 'CNC', 'quantity': 1, 'status': 'REJECTED', 'status_message': 'Price exceeds circuit limits for the instrument. Place an order within the daily range.', 'status_message_raw': 'RMS:R
				
			

The integration of WebSockets and threading within the Kite Connect API illustrates the modern evolution of trading systems towards more dynamic, real-time, and multitasking capabilities. 

Understanding and applying these concepts is essential for developing robust, efficient, and responsive automated trading applications in today’s fast-paced financial markets.

Post a comment

Leave a Comment

Your email address will not be published. Required fields are marked *

×Close