Kotak Neo API integration using Python

Are you a rule-based trader? Then you must be feeling bored executing the same kind of trades again and again. Kotak Neo API gives you the functionality to automate your strategies using Python. As we know, 95% of traders lose in the stock market, and the biggest reason for their loss is indiscipline. In today’s blog, I’ll show you how you can log in using Kotak Neo API, set up its WebSocket, and get live data as well.

The documentation for the Neo API is given on their GitHub page; you can access it from here.

Let’s Learn Kotak Neo Api Integration Using Python.

how to earn money 20240108 173944 0000

1.Installation: To install the Kotak Neo API, you need to first install Git. You can download Git from [here]. After installing Git, use the following command to install the neo_api_client.

				
					pip install "git+https://github.com/Kotak-Neo/kotak-neo-api.git#egg=neo_api_client"
				
			

After some time, you’ll receive a message confirming successful installation. Now, we’re all set to proceed to our next step which is integration of kotak neo api and integration of kotak neo websocket.

2. Credentials: Prior to logging in, gather your API key, referred to as the consumer key, along with the consumer secret, your login ID (your mobile number), and your login password. Initialize all of these values in variables for direct usage.

				
					Consumer_key = 'ABCDEFGHIJKLXXXXXXX'
Consumer_secret = 'XXXXXX'
Mobile = '95XXXXXXXX'
Password ='XYZ'
				
			

3. Login: To begin the login process, import NeoApi from neo_api_client as it contains all the relevant modules from the Kotak Neo API, as depicted Below.

				
					from neo_api_client import NeoAPI
				
			

4. Initialization: You can utilize the following code to initialize your login process, add your consumer key and consumer secret to it. After that, you’ll receive an OTP to initiate a new session.

				
					from neo_api_client import NeoAPI
def on_message(message):
    print(message)
    
def on_error(error_message):
    print(error_message)

def on_close(message):
    print(message)
    
def on_open(message):
    print(message)
    
#on_message, on_open, on_close and on_error is a call back function we will provide the response for the subscribe method.
# access_token is an optional one. If you have barrier token then pass and consumer_key and consumer_secret will be optional.
# environment by default uat you can pass prod to connect to live server
client = NeoAPI(consumer_key="", consumer_secret="", environment='uat',
                access_token=None, neo_fin_key=None)

# Initiate login by passing any of the combinations mobilenumber & password (or) pan & password (or) userid & password
# Also this will generate the OTP to complete 2FA
client.login(mobilenumber="+919999999999", password="XXXX")
				
			

5. Start Session: Enter your OTP in the provided section of the code below and execute it. Upon running this code, you’ll receive a confirmation message indicating successful login to your Kotak Neo account.

				
					# Setup Callbacks for websocket events (Optional)
client.on_message = on_message  # called when message is received from websocket
client.on_error = on_error  # called when any error or exception occurs in code or websocket
client.on_close = on_close  # called when websocket connection is closed
client.on_open = on_open  # called when websocket successfully connects
				
			
				
					OTP = '1234'
client.session_2fa(OTP="")
				
			

Once logged in, we’re empowered to fetch stock data and execute trades across diverse financial instruments using the Kotak Neo API. Accessing real-time market information and executing trades swiftly becomes seamless, offering a wide range of opportunities for analysis and trading across stocks, derivatives, commodities, and currencies.

6. Getting Symbols Data: Before placing any order, obtaining symbol data and symbol tokens is crucial. This information informs the API about the specific symbol or token for which you’re intending to place an order. To streamline this process, you can use the following code to retrieve all symbol data at once.

				
					#you can get this filepaths by running below command
client.scrip_master()
import pandas as pd
import urllib.request
from io import StringIO
file_paths = [
'https://lapi.kotaksecurities.com/wso2-scripmaster/v1/prod/2823-12-27/transformed/bse_cm.csv';,
'https://lapi.kotaksecurities.com/wso2-scripmaster/v1/prod/2823-12-27/transformed/cde_fo.csv',
'https://lapi.kotaksecurities.com/wso2-scripmaster/v1/prod/2823-12-27/transformed/mcx_fo.csv',
'https://lapi.kotaksecurities.com/wsol-scripmaster/v1/prod/2823-12-27/transformed/nse_cm.csv',
'https://lapi.kotaksecurities.com/wso2-scripmaster/v1/prod/2823-12-27/transformed/nse_fo.csv';, 
'https://lapi.kotaksecurities.com/wso2-scripmaster/v1/prod/2823-12-27/transformed/bse_fo.csv';
# Initialize an empty list to store DataFrames
dfs = []
#Download and read each CSV file
for file path in file paths:
    with urllib.request.urlopen(file_path) as response:
       content = response.read().decode("utf-8")
       df = pd.read_csv(StringIO(content))
           #Select specific columns
           selected_columns = df[["pSymbol","pExchSeg","pTrdSymbol", "pInstType", "llotSize", "pExpiryDate",
       # Convert 'pExpiry Date' to the desired format
       selected_columns.loc[:, 'pExpiryDate'] = pd.to_datetime(selected_columns["pExpiryDate'], unit='s')-
       # Append the selected columns DataFrame to the list
       dfs.append(selected_columns)
combined_database =pd.concat(dfs,   ignore_index=True)   
				
			

7.Get Live Quotes: The quotes API call fetches live quotes for the symbols you request. To subscribe to any symbol displayed below, you’ll need to provide token data in the specified format. Format for getting Nifty Quotes is given below. You can pass this symbols in quotes Api call and you will receive your desired data.

				
					instrument_tokens = [{"instrument_token": "26000", "exchange_segment": "nse_cm"}]
				
			
				
					client.quotes(instrument_tokens = instrument_tokens, quote_type="", isIndex=False, 
              callback=on_message, session_token="", sid
#you can check the response 

				
			

8. WebSocket: Utilizing WebSocket allows for receiving live quotes of symbols without the need for repeated requests, unlike the quotes API. Incorporate this code into your IDE to log in again to your Kotak Neo account. The data feed is received in the ‘message’ variable, requiring parsing to utilize it in our desired format. To store our data, we’re using a ‘live_data’ dictionary.

We will start login process again to let you know how websocket data is received in our “live_data” dictionary. 

				
					from threading import Thread
import time
def on_close(message):
    print("[OnClose]: ', message)
live_data = {}
def on_message(message):
    global live_data
    try:
        #print("Received message: (message}")
        for i in message:
            live_data[i['tk']] = i['ltp']

    except Exception as e:
        print("Error in on_message: {e}")
def on_error(message):
    result = message
    print("[OnError]: ', result)
client = NeoAPI(consumer_key=CK, consumer_secret=CS,
    environment="prod", on_message=on_message, on_error=on_error, , on_close=None, on_open=None)
ret =client.login(mobilenumber="+919999999999", password="XXXX")  
				
			

After Running this code do step number 5 again to Re-Login in your account. After successful login we will use threading and stream function to subscribe to our websocket as shown in the code below.

				
					inst_tokens = instrument_tokens #we initialise this earlier in our step 7
def stream():
    try:
        client.subscribe(instrument_tokens=inst_tokens, isIndex=False, isDepth=False)
    except Exception as e:
        print("Error while connecting to the WebSocket: {e}")
#Assuming you have a properly initialized `client` object elsewhere
Thread(target=stream).start()

				
			

Now You can subscribe to any token for which data is required like this and unsubscribe also as shown in below code. You can use my below listed YouTube video to get more information about websocket.

				
					client.subscribe(instrument_tokens = instrument_tokens, isIndex=False, isDepth=False)
# Un_Subscribes the given tokens. First the tokens will be checked weather that is subscribed. If not Subscribed we will send you the error message else we will unsubscribe the give tokens
client.un_subscribe(instrument_tokens=instrument_tokens)
				
			

9. Order Placement: You can now utilize your API to execute orders within your account. The codes required for placing orders and modifications are available on the GitHub page.

For a detailed tutorial on the Orders and Positions API, check out this video below.

10.Conclusion: This concludes our exploration into setting up and installing the Kotak Neo API using the Python programming language. Additionally, we delved into the intricacies of WebSocket setup using the Neo API. For more in-depth insights and tutorials, feel free to explore additional videos on my YouTube channel dedicated to algorithmic trading. Don’t forget to share these resources with your friends. Thank you for joining this learning journey!