Skip to main content

Upstox API Integration for Algo Trading: Complete Python Guide (2026)


Upstox API Integration for Algo Trading Python Guide


Algorithmic trading has transformed from an exclusive institutional luxury into an accessible playground for retail developers, quantitative hobbyists, and tech-savvy traders. In the Indian stock market ecosystem, Upstox stands out as one of the most developer-friendly discount brokers, offering a robust, low-latency API suite (v2/v3) equipped with comprehensive Python SDKs, lightning-fast REST endpoints, and high-performance WebSocket data streaming.

If you are looking to automate your trading strategies—whether you are executing momentum breakouts in Nifty options, running statistical arbitrage in equities, or building a custom TradingView webhook bridge—mastering Upstox API integration is your gateway.

In this comprehensive, hands-on guide, we will walk through every single moving part of building a production-grade algorithmic trading system using Upstox and Python.

1. Understanding the Upstox API Architecture

Before writing a single line of code, it is critical to understand how your application communicates with Upstox's servers. The Upstox Developer API is built on three core pillars:

  • REST API (v2 / v3): Used for synchronous, request-response operations such as user authentication, fetching account holdings, retrieving historical/intraday candle data, searching instruments, and placing or modifying orders.
  • WebSocket Streaming Feed (V3): Used for asynchronous, real-time streaming of live tick data (LTP, best bid/ask, volume, open interest) and order update callbacks with minimal network latency.
  • Python Client SDK (upstox-python): An official wrapper that abstracts raw HTTP requests into clean, object-oriented Python classes.

2. Prerequisites & Developer Account Setup

To begin your algo trading journey with Upstox, you need to set up your developer console:

  1. Active Upstox Demat Account: Ensure your account is fully KYC-verified and enabled for derivatives/equity trading.
  2. Upstox Developer Console: Head over to developer.upstox.com and log in with your credentials.
  3. Create an App: Register a new API app. Choose your app type (typically Non-Commercial or Commercial). Set your Redirect URL (e.g., http://127.0.0.1:8000/callback).
  4. Retrieve API Credentials: Note down your API Key (Client ID) and API Secret (Client Secret).

3. Step 1: OAuth2 Authentication & Access Token Generation

Upstox uses the OAuth 2.0 authorization framework. Because access tokens expire daily (typically valid for 24 hours), your authentication flow must handle token generation programmatically or via a quick local script each morning before markets open.

The Authorization URL

First, redirect your browser or user to the Upstox login consent screen:

https://api.upstox.com/v2/login/authorization/dialog?response_type=code&client_id=YOUR_API_KEY&redirect_uri=YOUR_REDIRECT_URL

Once authorized, Upstox redirects to your redirect_uri with an authorization code in the URL query parameters.

Exchanging Code for Access Token

Use Python's requests library to exchange this code for your bearer access token:

import requests

url = "https://api.upstox.com/v2/login/authorization/token"

payload = {
    'code': 'YOUR_AUTH_CODE_FROM_CALLBACK',
    'client_id': 'YOUR_API_KEY',
    'client_secret': 'YOUR_API_SECRET',
    'redirect_uri': 'YOUR_REDIRECT_URL',
    'grant_type': 'authorization_code'
}

headers = {
    'accept': 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded'
}

response = requests.post(url, data=payload, headers=headers)
data = response.json()

access_token = data.get('access_token')
print("Access Token:", access_token)

4. Step 2: Installing and Configuring the Official Python SDK

The official Upstox Python SDK simplifies API interactions. Install it directly via pip:

pip install upstox-python

Initialize your API client configuration with your retrieved access_token:

import upstox_client
from upstox_client.rest import ApiException

configuration = upstox_client.Configuration()
configuration.access_token = "YOUR_BEARER_ACCESS_TOKEN"

api_client = upstox_client.ApiClient(configuration)

5. Step 3: Fetching Instrument Keys and Market Data

Upstox uses unique Instrument Keys (e.g., NSE_EQ|INE669E01016 for TCS or NSE_FO|52195 for Nifty options) instead of traditional ticker symbols. Here is how to fetch historical or intraday candle data using HistoryApi:

from upstox_client.api.history_api import HistoryApi

try:
    history_api_instance = HistoryApi(api_client)
    instrument_key = "NSE_EQ|INE002A01018"
    interval = "day"
    to_date = "2026-03-31"
    
    api_response = history_api_instance.get_historical_candle_data1(
        instrument_key=instrument_key,
        interval=interval,
        to_date=to_date
    )
    print(api_response)
    
except ApiException as e:
    print(f"Exception when calling HistoryApi: {e}")

6. Step 4: Placing and Managing Orders via Python

Placing orders programmatically requires careful parameter definition. Here is a robust function to place a regular limit order:

from upstox_client.api.order_api import OrderApi
from upstox_client.models.place_order_request import PlaceOrderRequest

def place_limit_order(api_client, instrument_key, quantity, price):
    order_api = OrderApi(api_client)
    
    order_request = PlaceOrderRequest(
        quantity=quantity,
        product="I",
        validity="DAY",
        price=price,
        tag="algo_bot_v1",
        instrument_token=instrument_key,
        order_type="LIMIT",
        transaction_type="BUY",
        disclosed_quantity=0,
        trigger_price=0.0,
        is_amo=False
    )
    
    try:
        response = order_api.place_order(order_request, api_version='v2')
        print("Order placed successfully:", response)
        return response
    except ApiException as e:
        print(f"Failed to place order: {e}")
        return None

7. Step 5: Real-Time Tick Streaming via WebSockets

For latency-sensitive algorithmic trading, REST polling is too slow. You need Upstox's WebSocket V3 Feed:

import json
import ssl
import websocket
import upstox_client

def get_market_feed_authorize(api_client):
    api_instance = upstox_client.WebsocketApi(api_client)
    try:
        response = api_instance.get_market_data_feed_authorize(api_version='v2')
        return response.data.authorized_redirect_uri
    except ApiException as e:
        print(f"Error authorizing websocket: {e}")
        return None

8. Frequently Asked Questions (FAQs)

Q1: Is Upstox API free to use?

Yes, Upstox offers free API access for retail clients, though certain commercial or high-frequency tiers may have specific brokerage or subscription plans.

Q2: How do I handle daily access token expiration?

Because Upstox access tokens expire every 24 hours, you can automate token generation using headless browser automation or complete the manual morning OAuth redirect handshake.

Q3: Can I connect Upstox API to TradingView alerts?

Yes! You can set up a lightweight Flask or FastAPI webhook receiver on a cloud server that receives TradingView alert JSON payloads and executes OrderApi calls on Upstox instantly.


Atul Sharma

Written by Atul Sharma

Atul is a seasoned software engineer and quantitative finance enthusiast specializing in algorithmic trading infrastructure, Python automation, and low-latency market data pipelines in the Indian stock market.

Comments

Popular posts from this blog

FastAPI: How to Start with One Simple Project

FastAPI has rapidly gained popularity in the Python community, and for good reason. Designed to be fast, easy to use, and robust, it enables developers to build APIs quickly while maintaining code readability and performance. If you’re new to FastAPI, this guide walks you through setting up your first simple project from scratch. By the end, you’ll have a working REST API and the foundational knowledge to grow it into something more powerful. Why FastAPI? Before we dive into code, it’s worth understanding what sets FastAPI apart: Speed : As the name suggests, it's fast—both in development time and performance, thanks to asynchronous support. Automatic docs : With Swagger UI and ReDoc automatically generated from your code. Type hints : Built on Python type annotations, improving editor support and catching errors early. Built on Starlette and Pydantic : Ensures high performance and robust data validation. Prerequisites You’ll need: Python 3.7+ Basic knowledge of...

Vicharaks Axon Board: An Indian Alternative to the Raspberry Pi

  Vicharaks Axon Board: An Alternative to the Raspberry Pi Introduction: The Vicharaks Axon Board is a versatile and powerful single-board computer designed to offer an alternative to the popular Raspberry Pi. Whether you're a hobbyist, developer, or educator, the Axon Board provides a robust platform for a wide range of applications. Key Features: High Performance: Equipped with a powerful processor (e.g., ARM Cortex-A72). High-speed memory (e.g., 4GB or 8GB LPDDR4 RAM). Connectivity: Multiple USB ports for peripherals. HDMI output for high-definition video. Ethernet and Wi-Fi for network connectivity. Bluetooth support for wireless communication. Storage: Support for microSD cards for easy storage expansion. Optional onboard eMMC storage for faster read/write speeds. Expandable: GPIO pins for custom projects and expansions. Compatibility with various sensors, cameras, and modules. Operating System: Compatible with popular Linux distributions (e.g., Ubuntu, Debian). Support for o...

Mastering Error Handling in Programming: Best Practices and Techniques

 In the world of software development, errors are inevitable. Whether you're a novice coder or a seasoned developer, you will encounter errors and exceptions. How you handle these errors can significantly impact the robustness, reliability, and user experience of your applications. This blog post will explore the importance of error handling, common techniques, and best practices to ensure your software can gracefully handle unexpected situations. Why Error Handling is Crucial Enhancing User Experience : Well-handled errors prevent applications from crashing and provide meaningful feedback to users, ensuring a smoother experience. Maintaining Data Integrity : Proper error handling ensures that data remains consistent and accurate, even when something goes wrong. Facilitating Debugging : Clear and concise error messages help developers quickly identify and fix issues. Improving Security : Handling errors can prevent potential vulnerabilities that malicious users might exploit. Commo...