Zerodha provides a trading API known as Kite Connect, which allows developers to integrate Zerodha’s trading platform with their own applications and build custom trading strategies. Kite Connect API is available in various programming languages, including Python.
To use the Zerodha trading API in Python, you need to follow these steps:
Register as a Developer
- Before using the API, you need to sign up as a developer on Zerodha’s developer portal and obtain the API key and API secret.
- Signup / Kite Connect developer
Install Required Libraries
- You will need to install the kiteconnect library, which provides the Python interface for Kite Connect API. You can install it using pip:
pip install kiteconnect
Authenticate and Obtain Access Token
- To access Zerodha’s API, you need to authenticate your application using the API key and secret. This will generate an access token that allows you to interact with the API.
Access API Endpoints
- With the access token, you can access various API endpoints provided by Zerodha, such as fetching market data, placing orders, getting account information, and more.
Zerodha Kite API Code
Here’s a simple example of how to authenticate with the Zerodha API and fetch market data using Python:
import requests
from kiteconnect import KiteConnect
# API credentials
api_key = "your_api_key"
api_secret = "your_api_secret"
# Redirect URL for authentication
redirect_uri = "https://your-redirect-uri.com"
# Initialize KiteConnect
kite = KiteConnect(api_key=api_key)
# Generate the login URL for authentication
login_url = kite.login_url(redirect_uri)
# Print the login URL and manually open it in a browser
print("Login URL: ", login_url)
# After logging in, you will be redirected to the redirect_uri
# with the 'request_token' parameter in the URL.
# Fetch the 'request_token' from the URL
request_token = input("Enter the request token from the URL: ")
# Get the access token using the request token
data = kite.generate_session(request_token, api_secret=api_secret)
access_token = data["access_token"]
# Set the access token to the KiteConnect object
kite.set_access_token(access_token)
# Fetch market data (e.g., LTP of NIFTY 50)
data = kite.ltp("NSE:NIFTY50")
print("NIFTY 50 LTP: ", data["NSE:NIFTY50"]["last_price"])
In this example, we use the kiteconnect library to authenticate with Zerodha’s API, obtain the access token, and then use the access token to fetch the last traded price (LTP) of the NIFTY 50 index. The code is a simplified example and does not include error handling or other advanced features.
Please note that real trading involves risks, and it’s essential to thoroughly understand the API documentation, trading rules, and risk factors before implementing any trading strategy using the Zerodha API or any other trading API. Always test your code thoroughly in a demo or sandbox environment before using it in a live trading environment.