Upstox API Algo Trading Setup 2026 + Pine Bridge

jayadev rana Avatar

Upstox API algo trading means connecting your own code (or a TradingView strategy) to Upstox’s Developer API so orders fire automatically instead of you clicking Buy and Sell. As of July 2026 the stack is simple: register an app in the Upstox developer console, log in through OAuth 2.0 to get a daily access token, and send orders to the v3 order endpoint over HTTPS. Market-data and trading APIs have been free; a per-order charge applies on the order endpoint. You can also bridge TradingView Pine Script alerts to Upstox through a small Python relay running on a static IP. Below is the exact setup, working code, rate limits and the SEBI rules now in force.

In my 8 years coding Pine Script and wiring alerts into Indian broker APIs, Upstox is one of the cleaner REST APIs to automate — but the April 2026 regulatory changes (static IP, Algo-ID, daily token expiry) trip up almost everyone in the first week. Let me walk through what actually works today.

What you need for Upstox API algo trading in 2026

  • An active Upstox demat and trading account.
  • A Developer API app (created at the Upstox developer console) — this gives you an API key and API secret.
  • A redirect URI you control, for the OAuth callback.
  • A server or VPS with a registered static IP — mandatory for order placement since 1 April 2026.
  • Python 3.10+ with requests (and flask if you want the TradingView bridge).
  • For TradingView alerts: a Pro, Pro+ or Premium TradingView plan, because webhooks are a paid feature.

Upstox API pricing in 2026: free or paid?

Upstox kept its Developer API unusually cheap through a long promotional window: market-data and trading APIs were free, and orders placed via API were charged a flat ₹10 per order — a rate Upstox extended through 31 March 2026. That promotional window has now closed.

So as of July 2026, do not hard-code a price you read in a blog. Confirm the live figure on the Upstox Charges page or the brokerage-details endpoint before you size your strategy. For context, Upstox’s standard brokerage is ₹20 per executed order on equity intraday and F&O, while market-data and websocket APIs have historically stayed free. If you are comparing brokers on cost and throughput, I keep an updated breakdown in my Zerodha Kite Connect API pricing and rate limits guide.

Step 1: Authentication (OAuth 2.0 and the daily token)

Upstox uses the OAuth 2.0 authorization-code flow. You send the user to the Upstox login dialog, they log in with 2FA, and Upstox redirects back to your redirect_uri with a single-use code. Your server then exchanges that code for an access_token.

The catch that bites everyone: the access token expires at 3:30 AM IST the next day, no matter when you generated it. There is no long-lived token for the order flow — you re-authenticate every trading day. I have seen setups silently stop trading overnight because nobody refreshed the token before the open.

Login dialog URL (send the user here):

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

Exchange the returned code for a token:

import requests

def get_access_token(auth_code, api_key, api_secret, redirect_uri):
    url = "https://api.upstox.com/v2/login/authorization/token"
    headers = {
        "accept": "application/json",
        "Content-Type": "application/x-www-form-urlencoded",
    }
    data = {
        "code": auth_code,
        "client_id": api_key,
        "client_secret": api_secret,
        "redirect_uri": redirect_uri,
        "grant_type": "authorization_code",
    }
    resp = requests.post(url, headers=headers, data=data, timeout=10)
    resp.raise_for_status()
    # Token is valid only until 3:30 AM IST the next day
    return resp.json()["access_token"]

Step 2: Place an order with the v3 API

The current order endpoint is POST https://api-hft.upstox.com/v3/order/place. It supports MARKET, LIMIT, SL and SL-M order types, product codes I (intraday), D (delivery) and MTF, and validity DAY or IOC. The response returns one or more order_ids plus a latency figure in the metadata so you can measure round-trip time.

def place_order(access_token, instrument_token, side, qty, algo_name=None):
    url = "https://api-hft.upstox.com/v3/order/place"
    headers = {
        "Authorization": f"Bearer {access_token}",
        "Content-Type": "application/json",
        "Accept": "application/json",
    }
    # X-Algo-Name is required only for an exchange-approved algo strategy
    if algo_name:
        headers["X-Algo-Name"] = algo_name

    payload = {
        "quantity": qty,
        "product": "I",              # I=intraday, D=delivery, MTF
        "validity": "DAY",
        "price": 0,                  # 0 for MARKET orders
        "instrument_token": instrument_token,  # e.g. "NSE_EQ|INE528G01035"
        "order_type": "MARKET",
        "transaction_type": side,    # "BUY" or "SELL"
        "disclosed_quantity": 0,
        "trigger_price": 0,
        "is_amo": False,
        "slice": False,
    }
    resp = requests.post(url, headers=headers, json=payload, timeout=10)
    resp.raise_for_status()
    return resp.json()

# Example: buy 1 unit at market
# print(place_order(token, "NSE_EQ|INE528G01035", "BUY", 1))

You fetch each instrument_token from Upstox’s daily instruments (BOD) master file — never hard-code them, because F&O tokens change on expiry.

Rate limits and the 10-orders-per-second line

Rate limits are enforced per-API and per-user. For live data (quotes, historical candles, positions, holdings) you get generous throughput in the tens of requests per second. The order-placement family — Place, Modify, Cancel, Multi-Order and GTT — shares a combined limit that follows the NSE circular of 5 May 2025.

The number that matters for classification: if your algo places fewer than 10 orders per second, it is a regular retail algo and needs no exchange registration. Cross 10 orders per second and you are in HFT territory, which requires formal exchange approval. Almost every retail Pine Script or Python strategy sits comfortably under this line.

Building or fixing an Upstox bridge and getting orders rejected on the static-IP check? I set up and debug these for traders every week. Message me on WhatsApp at +91 77352 68199 with a description of your strategy and I will tell you exactly what your setup needs.

SEBI 2026 rules every Upstox API user must follow

SEBI’s retail-algo framework became fully mandatory on 1 April 2026, and Upstox has implemented it. The broker is now responsible for every algo routed through its platform, so these requirements are non-negotiable:

Requirement Regular retail algo (under 10 orders/sec) HFT algo (over 10 orders/sec)
Exchange registration Not required Mandatory
Algo-ID Broker / app level Exchange-assigned, per strategy
Static IP for order APIs Required Required
OAuth 2.0 + 2FA login Required (daily) Required (daily)
X-Algo-Name header Only if approved algo Required

Two practical points. First, every API order must originate from a registered static IP — you get one primary and one optional secondary IP per account, you can change them only once per calendar week, and changing an IP invalidates your existing tokens. Orders from unregistered IPs are rejected. Second, sessions use OAuth with 2FA and expire daily, so a build-once-and-forget-it script will not survive. If you are also automating Zerodha, Angel One or Fyers, the same broad SEBI rules apply — I cover the Fyers side in my Fyers webhook automation guide.

Bridging TradingView Pine Script alerts to Upstox

You cannot point a TradingView webhook straight at Upstox. TradingView fires alerts from its own rotating IPs, and — because of the static-IP rule — Upstox will reject orders that do not come from your registered address. The fix is a thin relay: TradingView sends its alert to a small Flask app on your static-IP VPS, the relay validates it, then calls the Upstox order API.

The proven architecture is: Pine Script alert → HTTPS webhook → validation layer (secret + dedupe + risk checks) → Upstox v3 order. A well-built relay clocks 200–500 ms from alert firing to order acknowledgement.

The Flask relay

import os, hmac, requests
from flask import Flask, request, abort

app = Flask(__name__)
WEBHOOK_SECRET = os.environ["TV_WEBHOOK_SECRET"]
UPSTOX_TOKEN   = os.environ["UPSTOX_ACCESS_TOKEN"]   # refreshed daily
ORDER_URL      = "https://api-hft.upstox.com/v3/order/place"
_seen = set()   # in-memory dedupe; use Redis in production

@app.route("/tv-upstox", methods=["POST"])
def relay():
    data = request.get_json(force=True)

    # 1) Authenticate the alert with a shared secret
    if not hmac.compare_digest(data.get("secret", ""), WEBHOOK_SECRET):
        abort(403)

    # 2) Idempotency: drop duplicate fires of the same alert
    if data.get("id") in _seen:
        return {"status": "duplicate ignored"}, 200
    _seen.add(data.get("id"))

    # 3) Map the alert to an Upstox order
    payload = {
        "quantity": int(data["qty"]),
        "product": "I",
        "validity": "DAY",
        "price": 0,
        "instrument_token": data["instrument_token"],
        "order_type": "MARKET",
        "transaction_type": data["side"].upper(),
        "disclosed_quantity": 0,
        "trigger_price": 0,
        "is_amo": False,
        "slice": False,
    }
    headers = {
        "Authorization": f"Bearer {UPSTOX_TOKEN}",
        "Content-Type": "application/json",
        "Accept": "application/json",
    }
    r = requests.post(ORDER_URL, json=payload, headers=headers, timeout=10)
    return r.json(), r.status_code

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)

The TradingView alert message

In your Pine Script strategy’s alert, set the webhook URL to https://your-vps-domain/tv-upstox and paste this JSON as the alert message:

{
  "secret": "your-long-random-secret",
  "id": "{{timenow}}",
  "instrument_token": "NSE_EQ|INE528G01035",
  "side": "BUY",
  "qty": 1
}

Use strategy.entry / strategy.exit or alertcondition() in Pine Script v6 to trigger these. If your Pine logic needs cleaning up or converting into reliable alert signals first, that is exactly the kind of work I do on my Pine Script development service; for MetaTrader users I run a parallel MT4/MT5 automation service.

A workflow that survives real trading

The pattern I trust: a scheduled job re-authenticates before 9:00 AM and stores the fresh token; the Flask relay reads that token, checks the shared secret, dedupes on alert ID, enforces a max-position guard, logs every request and response, and only then calls the order API. Run it on a VPS whose static IP is registered in your Upstox app. Test everything in the Upstox sandbox before you point a live strategy at it — market orders are unforgiving.

Frequently asked questions

Is Upstox API free for algo trading?

Market-data and trading APIs have been free to use. Order placement carried a flat ₹10-per-order promo that ran until 31 March 2026; as of July 2026, check the live Upstox Charges page for the current per-order rate, since that window has closed.

How long is the Upstox access token valid?

Until 3:30 AM IST the following day, regardless of when you generated it. You must re-run the OAuth login every trading day — there is no permanent token for order placement.

Can I connect TradingView directly to Upstox?

No. TradingView’s webhook IPs are dynamic, and Upstox now requires orders to come from your registered static IP. You need a relay — a small Flask app on a static-IP VPS — between TradingView and the Upstox order API.

Do I need SEBI registration to run an Upstox API algo?

Not if your strategy places fewer than 10 orders per second, which is a regular retail algo. Above 10 orders per second you are classed as HFT and need exchange approval and an exchange-assigned Algo-ID.

Which Upstox API endpoint places orders?

The v3 endpoint: POST https://api-hft.upstox.com/v3/order/place, sent with a Bearer access token. It returns the order IDs and a latency figure in the response metadata.

Get your Upstox bridge built

Want your Upstox API algo trading bridge built, tested and SEBI-compliant? Across 8 years I have coded 7,700+ strategies and automated broker pipelines for clients in 14+ countries. WhatsApp me at +91 77352 68199 with your TradingView strategy or Python logic and I will get it live.

Risk disclaimer

Trading in equities, futures and options carries a substantial risk of loss and is not suitable for every investor. Automated and algorithmic strategies can fail, misfire or amplify losses due to bugs, connectivity issues or market conditions. Nothing here is investment advice or a guarantee of profit. Code samples are illustrative, may change as Upstox updates its API, and must be tested in a sandbox before live use. Trade only with capital you can afford to lose, and ensure your setup complies with current SEBI and exchange rules.

Leave a Reply

Your email address will not be published. Required fields are marked *