top of page

How to Automate Trading using the Kotak Securites API

This post will share a code and also explain you the basic outline that you can follow to trade on the kotak securities platform using their free API

To run the above code in a live trading environment, you can follow these steps:

1. Ensure your trading strategy has been thoroughly backtested and optimized.

2. Make sure you have appropriate risk management in place.

3. Modify the code to fetch real-time data instead of historical data.

4. Implement an event loop to continuously fetch real-time data and check for buy and sell signals.

Here's an example of how you can code to run in a live trading environment:

import time
import pandas as pd
from ks_api_client import ks_api_client
from datetime import datetime

# Replace with your credentials
username = 'YOUR_USERNAME'
password = 'YOUR_PASSWORD'
api_key = 'YOUR_API_KEY'
user_key = 'YOUR_USER_KEY'

# Initialize the API
client = ks_api_client(username, password, api_key, user_key)

# Log in

# Replace these parameters with your desired settings
symbol = 'RELIANCE.NSE'
short_ma_length = 10
long_ma_length = 30
interval = 300  # Fetch data every 5 minutes (300 seconds)

# Function to calculate buy and sell signals based on moving averages
def moving_average_signals(data, short_ma_length, long_ma_length):
    short_ma = data['close'].rolling(window=short_ma_length).mean()
    long_ma = data['close'].rolling(window=long_ma_length).mean()

    buy_signal = (short_ma > long_ma) & (short_ma.shift(1) <= long_ma.shift(1))
    sell_signal = (short_ma < long_ma) & (short_ma.shift(1) >= long_ma.shift(1))

    return buy_signal, sell_signal

# Initialize the data frame
data = pd.DataFrame(columns=['date', 'open', 'high', 'low', 'close', 'volume'])

while True:
    # Fetch the latest data
    current_data = client.ltp(symbol)
    latest_bar = {
        'date': current_data['Timestamp'],
        'open': current_data['O'],
        'high': current_data['H'],
        'low': current_data['L'],
        'close': current_data['C'],
        'volume': current_data['V']
    data = data.append(latest_bar, ignore_index=True)

    # Calculate buy and sell signals
    buy_signal, sell_signal = moving_average_signals(data, short_ma_length, long_ma_length)

    # Check the latest signals
    if buy_signal.iloc[-1]:
        print("Buy signal")
        # Place a buy order using the SDK functions
        # ...

    if sell_signal.iloc[-1]:
        print("Sell signal")
        # Place a sell order using the SDK functions
        # ...

    # Wait for the next interval

This code will run indefinitely, fetching real-time data every 5 minutes (or the specified `interval`) and checking for buy and sell signals. You can adjust the `interval` variable to control how often the code fetches data and checks for signals.

Please be aware that trading in a live environment carries risks. Make sure you thoroughly test and optimize your strategy in a backtesting environment before running it live. Additionally, implement appropriate risk management measures, such as stop-loss and take-profit orders, to protect your capital.

You can run the above code in Google Colab for live trading. However, there are a few things to keep in mind when using Google Colab for live trading:

1. Session time limit: Google Colab sessions are limited to 12 hours for free users and 24 hours for Pro users. If you want to run the code continuously for more than the session time limit, you'll need to restart the session and run the code again.

2. Inactivity timeout: Google Colab sessions automatically disconnect after 90 minutes of inactivity. If you're not actively working on the notebook, your session may be terminated, stopping the live trading code.

3. Privacy and security: Google Colab is a cloud-based service, so you'll need to upload your API keys and other sensitive information to the platform. Make sure you understand the potential risks associated with storing sensitive information on a third-party platform.

4. Dependency management: You'll need to install any required Python packages in the Google Colab environment. You can do this using `!pip install package_name` in a code cell.

To set up the code in Google Colab:

1. Open Google Colab ( and create a new notebook.

2. In a code cell, install the Kotak Securities Python SDK using the following command:

!pip install ks_api_client

3. Copy and paste the modified live trading code from the previous response into a new code cell in the notebook.

4. Replace the placeholder values (`YOUR_USERNAME`, `YOUR_PASSWORD`, `YOUR_API_KEY`, and `YOUR_USER_KEY`) with your actual Kotak Securities API credentials.

5. Adjust any other necessary parameters, such as `symbol`, `short_ma_length`, and `long_ma_length`.

6. Run the code cell to start the live trading loop.

Keep in mind the limitations and considerations mentioned above when using Google Colab for live trading. It's essential to thoroughly test your strategy in a backtesting environment before running it live and implement appropriate risk management measures to protect your capital.

40 views0 comments


Commenting has been turned off.
bottom of page