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:
- Active Upstox Demat Account: Ensure your account is fully KYC-verified and enabled for derivatives/equity trading.
- Upstox Developer Console: Head over to developer.upstox.com and log in with your credentials.
- 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). - 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.
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
Post a Comment