SplashAlgo

Powered by TheCodingView

SplashAlgoPowered by TheCodingView

How to Use Upstox API for Automated Trading: A Comprehensive Tutorial

Published on: 28th Aug 2024

title image

In this blog series, we'll explore how we can leverage Python and Upstox Broker APIs to automate your trading. We'll cover everything from setting up our api keys to implementing basic trading strategies and executing real-time trades. Whether you're a seasoned programmer or a trading enthusiast looking to dip your toes into coding, this guide will help you take control of your trading through automation. To use the Upstox APIs, you need an API key, which can be generated through the broker's terminal.

Generating API key

To generate an API key and secret key, log in to the Upstox Terminal using your Upstox credentials.

upstox login page

After logging in, enter the OTP sent to your registered mobile number.

upstox otp

You will then be prompted to enter your MPIN for authorization. Enter the MPIN you set up in your Upstox mobile app.

upstox mpin

After successfully logging in, you will be redirected to the homepage. Click on your username in the top-right section of the page, and then select "My Account."

upstox dashboard

Click on "My Account" to be redirected to your profile section. At the top, you'll see an "Apps" tab. Click on "Apps," and you'll be taken to a page where your apps are listed. If you haven't created any apps before, the list will be empty.

upstox new app

To access the API key and secret, you first need to create an app. Click on the "New App" button. A form will appear where you'll need to enter details like the App Name, Redirect URL, and other optional fields.

upstox app creation

We'll name the app "Demo App." For the Redirect URL, enter https://upstox.com. The other fields are optional, so we'll leave them as they are. After that, accept the terms and conditions, and click "Continue." That's it—you've created an app, and your API key and secret have been generated. You should see something like this.

upstox api key

Keep these credentials safe and never disclose them to anyone, as they can be used to access your apps and trading account.

Getting started

To start using the Upstox API with Python, ensure that Python is installed on your system. You can download and install Python from here. After installing Python, you'll need the requests module to send API requests to the Upstox API. To install it, run the following command in the terminal:

pip install requests

Step by Step Guide to authenticate using Upstox API with python

The authentication process for Upstox API consists of two steps:

  1. Login URL generation:

The first step in authenticating with the Upstox API involves constructing a login URL. You need to include your API key, redirect URL, and set the response_type parameter to "code" in the URL. The Upstox documentation provides a sample URL to illustrate the required format.

Here's an example of how the URL should look:

https://api.upstox.com/v2/login/authorization/dialog?response_type=code&client_id=615b1297-d443-3b39-ba19-1927fbcdddc7&redirect_uri=https%3A%2F%2Fwww.trading.tech%2Flogin%2Fupstox-v2&state=RnJpIERlYyAxNiAyMDIyIDE1OjU4OjUxIEdNVCswNTMwIChJbmRpYSBTdGFuZGFyZCBUaW1lKQ%3D%3D

*Note: In this context, the terms api_key and client_id are used interchangeably. client_id refers to the API key you generated earlier, not the user ID displayed in the Upstox dashboard. The Upstox API expects you to pass the API key as client_id.

We can use Python to construct the URL programmatically instead of hardcoding it. Here's an example of how to do this:

client_id = "<YOUR_API_KEY>"
client_secret = "<YOUR_API_SECRET>"
redirect_url = "<your app redirect URL>"
response_type = "code"
login_url = f"https://api.upstox.com/v2/login/authorization/dialog?response_type={response_type}&client_id={client_id}&redirect_uri={redirect_uri}"
print(login_url)

Running the script will print the login_url in the console. Copy this URL and paste it into a browser tab, then press Enter. This will take you to the Upstox login screen. After entering your credentials and logging in, you'll be redirected to the homepage. However, what you're interested in is the URL displayed in the browser's address bar, which will look something like this:

https://upstox.com?code=AB3342

upstox auth code

Copy the code from the URL in the browser's address bar, as you will need it for the next step: generating the access token.

2. Generating Access Token

With the authorization code in hand, you can now send a POST request to Upstox to generate an access token. This token will be used for subsequent requests to the Upstox API.

Here’s an example of how to do this using Python and the requests module:

import requests
token_url = f"https://api-v2.upstox.com/login/authorization/token"
authCode = "<your auth code>"
headers = {
    'accept': "application/json",
    "Api-Version": "2.0",
    "Content-Type": 'application/x-www-form-urlencoded'
}
data = {
    'code': authCode,
    "client_id": client_id,
    "client_secret": client_secret,
    "redirect_uri": redirect_url,
    "grant_type": "authorization_code"
}
resp = requests.post(token_url, headers=headers, data=data).json()
access_token = resp.get("access_token")
print(access_token)

Replace 'YOUR_API_KEY', 'YOUR_API_SECRET', and 'YOUR_AUTHORIZATION_CODE' with your actual API key, API secret, and the authorization code you obtained. This script will print the access token, which you’ll use for subsequent API requests.

The access token is valid until 3:30 A.M. IST following day, as suggested by the Upstox Documentation. So, even if you generated the access token at 2:00 A.M., it will be expired at 3:30 A.M.

This access token will be required while sending any request to the Upstox API.

Fetching Historical Data from Upstox Api

For fetching historical data from Upstox api, we do not require to pass access token in the request. This is because Upstox has intentionally made the historical data API open to general public, meaning anyone can fetch data without any authorization. All we have to do is pass the following query parameters in the URL:

Name

Description

instrument_key

Include the symbol name of the financial instrument in your request to fetch the relevant data.

interval

The timeframe for which we are querying the data for. Possible values: 1minute, 30minute, day, week, month.

to_date

The date up to which we want the historical data. Format: YYYY-MM-DD

from_date (Optional)

The starting date for the historical data. Format: YYYY-MM-DD.

The instrument_key must be formatted correctly in the request to ensure the correct instrument and exchange segment are used. Here’s how to pass it:

Name

Pattern

NSE stocks & Equities

NSE_EQ|<ASSET_KEY>

For example: NSE_EQ|INE839G01010

NSE Index

NSE_INDEX|<INDEX_TOKEN>

Example: NSE_INDEX|NIFTY50, NSE_INDEX|BANKNIFTY

NSE Options

NSE_FO|<OPTIONS_TOKEN>

Example: NSE_FO|49931

BSE Index

BSE_INDEX|SENSEX

MCX Futures

MCX_FO|<token>

Here’s a concise example of how to fetch historical data using the provided information in Python:

import requests
import pandas as pd
instrument_key = "NSE_EQ|INE839G01010"
interval = "day"
to_date = "2024-08-12"
from_date = "2024-07-12"
url = f"https://api.upstox.com/v2/historical-candle/{instrument_key}/{interval}/{to_date}/{from_date}"
headers = {
    "Accept": "application/json"
}
resp = requests.get(url).json()
# Extract the candle data
candles = resp['data']['candles']
# Convert to DataFrame, excluding the last column
df = pd.DataFrame(candles, columns=['Date', 'Open', 'High', 'Low', 'Close', 'Volume', "OI"])
print(df)


And here is the output:

data table

To interact with the Upstox order API for placing, modifying, and canceling orders, you'll use specific endpoints provided by Upstox. Here’s a general overview and examples of how to handle these tasks in Python:

Order API

Place order

To place an order with the Upstox API, you'll need to include headers and body parameters and send a POST request to the endpoint https://api-hft.upstox.com/v2/order/place. Here’s how you can do this:

import requests
import json
order_url = f"https://api-hft.upstox.com/v2/order/place"
headers = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json",
"Accept": "application/json"
}
data = {
"quantity": 1,
"product": "D",
"validity": "DAY",
"instrument_token": "NSE_EQ|INE848E01016 ",
"order_type": "MARKET",
"transaction_type": "BUY",
 "disclosed_quantity": 0,
 "trigger_price": 0,
 "is_amo": false
}
resp = requests.post(order_url, headers=headers, data=json.dumps(data))
print(resp.json())

If the order is placed successfully, we will get the response similar to this:

{
  "status": "success",
  "data": {
    "order_id": "1644490272000"
  }
}

When you want to modify an order, you'll need to include the order_id of the order you wish to modify. Here's a guide on how to handle modifying an order using the Upstox API:

Modify an Order

To modify an order with the Upstox API, follow these steps:

  1. Headers: Include authorization and content type in the headers.

  2. Body Parameters: Include the order_id and other parameters you wish to update.

  3. Endpoint: Send a POST request to https://api-hft.upstox.com/v2/order/modify.

Here's an example of how to modify an order:

import requests, json
modify_order_url = f"https://api-hft.upstox.com/v2/order/modify"
headers = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json",
"Accept": "application/json"
}
data = {
  "quantity": 1,
  "validity": "DAY",
  "price": 120.01,
  "order_id": "1644490272000",
  "order_type": "MARKET",
  "disclosed_quantity": 0,
  "trigger_price": 0
}
resp = requests.put(modify_order_url, headers=headers, data=data)

You will get the following response, if the order is modified successfully:

{
  "status": "success",
  "data": {
    "order_id": "1644490272000"
  }
}

Cancel Order

Cancelling an order is fairly simple, you can cancel an existing order as follows:

  1. Headers: Include authorization and content type in the headers.

  2. Body Parameters: Include the order_id and other parameters you wish to update.

  3. Endpoint: Send a POST request to https://api-hft.upstox.com/v2/order/cancel.

import requests, json
url = "https://api-hft.upstox.com/v2/order/cancel"
headers = {
    "Accept": "application/json", 
    "Authorization": f"Bearer {access_token}"
}
data = {
    "order_id": "1644490272000"
}
resp = requests.delete(url, headers=headers, data=json.dumps(data))
print(resp.text)

And the response will be as follows:

{
  "status": "success",
  "data": {
    "order_id": "1644490272000"
  }
}

This is how we can leverage the Upstox API to automate placing orders, fetch data, and integrate our own strategies to streamline trading. Next, we'll explore how to use the WebSocket API to access real-time data and further automate our trading strategies, eliminating the need for manual buy and sell actions.

*Note: The logo used in the title image of this blog is a property of Upstox Broker. We do not own the registered trademark logo. The Python logo used in the title image is a trademark of the Python Software Foundation.

SplashAlgo

Powered by TheCodingView

SplashAlgo offer trading signals, indicators and execution engines to help improve your trading strategies. Our tools provide real-time market insights to help you make informed decisions. Join us to enhance your trading experience!

PRODUCTS

Indicators

Flickerr Signals

Screeners

USEFUL LINKS

Your account

Become an affiliate

FAQ


2024 Copyright | SplashAlgo

About Us

Disclaimer

Terms of Service

Privacy Policy