⚡ Quick Answer — Bottom Line Up Front

Dhan DhanHQ API wins for options traders and F&O strategies — superior market depth data, excellent options chain API, and a more intuitive Python SDK. Upstox API wins for equity algo traders and data scientists — higher REST rate limits (25 req/sec), better historical data (2-year 1-minute candles vs Dhan's 30 days), and a cleaner OpenAPI-based interface. Both are completely free with zero monthly API fees.

1. API Overview

Dhan (DhanHQ) launched its API in 2022 and quickly gained traction among F&O and options traders for its comprehensive options chain and market depth data. Upstox, backed by Tiger Global and Ratan Tata, has offered a developer API since 2017 and is popular with equity algo traders for its cleaner REST interface and higher historical data depth.

Source: Official DhanHQ and Upstox developer documentation, October 2026
Feature 🟠 Dhan DhanHQ API 🟣 Upstox API
API Launch Year 2022 2017 MORE MATURE
API Architecture REST + WebSocket v2 (OnMarketUpdate) REST + WebSocket (Market Data Feeder v2)
Official Python SDK ✅ dhanhq (PyPI) ✅ upstox-python-sdk (PyPI)
OpenAPI Spec ✅ Available ✅ Full OpenAPI 3.0 spec BETTER
Markets Supported NSE, BSE, NFO, BFO, MCX, CDS NSE, BSE, NFO, BFO, MCX, CDS TIE
Paper Trading Mode ✅ Forever-free paper trading ❌ No sandbox
Specialization Options & F&O focus Equity & data focus

2. Pricing & Cost

The great news: both platforms are completely free for API access. Neither charges monthly subscription fees for order placement, market data, or WebSocket streaming.

All prices in INR. Both APIs are free as of October 2026.
Cost Component 🟠 Dhan DhanHQ API 🟣 Upstox API
Order Placement API ₹0 FREE ₹0 FREE
Historical Data API ₹0 FREE ₹0 FREE
Real-time WebSocket ₹0 (OnMarketUpdate) ₹0 (Market Data Feeder)
Options Chain API ₹0 FREE ₹0 FREE
Total Monthly API Cost ₹0 TIE ₹0
Intraday Equity Brokerage ₹20/order flat or 0.03% ₹20/order flat or 0.05%
F&O Brokerage ₹20/order flat ₹20/order flat TIE

3. WebSocket Latency Analysis

WebSocket latency — the time between an exchange matching a trade and your algo receiving the tick — determines how quickly your strategy can react to market events. Both Dhan and Upstox route data through co-located servers at NSE/BSE data centers. Here is what real-world community benchmarks show:

Community-reported latency benchmarks. Results vary based on client network and server location. Measured from exchange timestamp to Python on_message callback.
Latency Metric 🟠 Dhan DhanHQ 🟣 Upstox
Typical tick latency (Mumbai VPS) 5–15ms 8–25ms
Tick frequency (NIFTY Futures) Up to 60 ticks/second Up to 50 ticks/second
WebSocket protocol Binary (Protobuf) Binary (Protobuf)
Message format Protobuf + JSON fallback Protobuf v2
Auto-reconnect ✅ Built-in reconnect logic ✅ Built-in reconnect logic TIE
Ping/heartbeat interval 25 seconds 30 seconds
Connection stability (weekday average) 99.3% uptime observed 99.1% uptime observed
💡 Latency context: For most retail algo strategies (EMA crossovers, momentum, mean reversion, options hedging), 5–25ms WebSocket latency is perfectly adequate. True high-frequency trading (microsecond latency) requires exchange co-location and is not accessible via retail broker APIs.

WebSocket Latency Benchmark Script

Python — Latency Benchmarking
"""Measure WebSocket tick-to-callback latency for any broker."""
import time
import statistics
from datetime import datetime

class LatencyBenchmark:
    def __init__(self):
        self.latencies = []

    def on_tick(self, exchange_ts: int, recv_ts: float):
        """Call this in your on_message callback."""
        exchange_ms = exchange_ts / 1000.0
        recv_ms     = recv_ts * 1000.0
        latency_ms  = recv_ms - exchange_ms
        if 0 < latency_ms < 5000:  # Sanity filter
            self.latencies.append(latency_ms)

    def report(self, n_samples: int = 1000):
        if len(self.latencies) < n_samples:
            return None
        sample = self.latencies[-n_samples:]
        return {
            "p50_ms":  round(statistics.median(sample), 2),
            "p95_ms":  round(sorted(sample)[int(n_samples * 0.95)], 2),
            "p99_ms":  round(sorted(sample)[int(n_samples * 0.99)], 2),
            "mean_ms": round(statistics.mean(sample), 2),
            "min_ms":  round(min(sample), 2),
            "max_ms":  round(max(sample), 2),
        }

bench = LatencyBenchmark()
# Inside your on_message callback:
# bench.on_tick(message["exchange_timestamp"], time.time())
# Every 1000 ticks:
# print(bench.report())

4. Rate Limits & Throughput

Rate limits as per official API documentation, October 2026.
Limit Type 🟠 Dhan DhanHQ 🟣 Upstox
REST API calls per second ~15 req/sec 25 req/sec WINNER
Orders per day No hard limit documented 250 orders/day (standard accounts)
WebSocket subscriptions 1,000 instruments/connection 1,000 instruments/connection TIE
WebSocket connections per key 1 concurrent 1 concurrent TIE
Historical data requests/min 25 req/min 25 req/min TIE
Order modification rate 10 modifications/sec 5 modifications/sec
⚠️ Upstox order limit: Upstox’s 250 orders/day limit for standard accounts can be a bottleneck for high-frequency intraday strategies. Contact Upstox support to request a higher limit for active algo accounts. Dhan currently has no documented daily order cap.

5. Historical Data Depth

Data Feature 🟠 Dhan DhanHQ 🟣 Upstox
1-minute candle history 30 days 2 years (730 days) WINNER
Daily candle history 10+ years 10+ years TIE
Intraday intervals 1min, 5min, 15min, 30min, 60min 1min, 30min, 60min, 1day, 1week, 1month MORE INTERVALS
NSE/BSE equity instruments ✅ All ✅ All TIE
F&O historical data ✅ Yes (Options OHLC) ✅ Yes
Tick-level data (sub-minute) ❌ Not available ❌ Not available TIE
💡 Backtesting implication: Upstox’s 2-year 1-minute historical data is a major advantage for backtesting intraday strategies. Dhan’s 30-day limit on 1-minute candles means you need an alternative data source (e.g., NSEpy, Quandl, or a paid data vendor) for longer backtests.

6. Options Chain & F&O Features

For options traders, the quality of options chain data APIs can be a decisive factor. Dhan has invested heavily in F&O features:

F&O Feature 🟠 Dhan DhanHQ 🟣 Upstox
Options chain API ✅ Full NSE/BSE options chain WINNER ✅ Options chain via market quote
Greeks (Delta, Gamma, Theta, Vega) ✅ Available in options chain API WINNER ❌ Not in standard API (compute client-side)
OI (Open Interest) data ✅ Real-time OI in WebSocket ✅ Real-time OI
ATM strike detection ✅ API auto-identifies ATM Manual computation
F&O margin calculator API ✅ Yes (SPAN + Exposure) ❌ Not available
Multi-leg order basket ✅ Basket orders supported ❌ Leg-by-leg only

7. Python Code: Dhan DhanHQ API

Python — Dhan DhanHQ Full Setup
"""Dhan DhanHQ API — install: pip install dhanhq pandas"""
from dhanhq import dhanhq, marketfeed
import pandas as pd

# Initialize
client_id    = "YOUR_CLIENT_ID"
access_token = "YOUR_ACCESS_TOKEN"   # From DhanHQ console

dhan = dhanhq(client_id, access_token)

# Fetch historical 5-min candles for NIFTY Futures
hist_data = dhan.historical_daily_data(
    symbol="NIFTY",
    exchange_segment="NSE_FNO",
    instrument_type="FUTIDX",
    expiry_code=1,       # 1=near month expiry
    from_date="2026-09-01",
    to_date="2026-10-19"
)
df = pd.DataFrame(hist_data["data"])
print(df.tail())

# Fetch options chain for NIFTY
chain = dhan.option_chain(
    underlying_scrip=13,    # NIFTY underlying
    underlying_seg="IDX_I", # Index
    expiry="2026-10-31"
)
print(f"NIFTY ATM: {chain['data']['at_the_money_strike']}")

# Place a buy order for NIFTY Call option
order_response = dhan.place_order(
    security_id="36081",      # NIFTY 24000 CE token
    exchange_segment=dhan.NSE_FNO,
    transaction_type=dhan.BUY,
    quantity=50,              # 1 lot = 50 units
    order_type=dhan.MARKET,
    product_type=dhan.INTRA,
    price=0
)
print(f"Dhan order: {order_response['data']['orderId']}")

Dhan WebSocket Real-Time Feed

Python — Dhan OnMarketUpdate WebSocket
from dhanhq import marketfeed import asyncio # Instrument list: (exchange_segment, security_id, feed_type) instruments = [ (marketfeed.NSE, "13", marketfeed.Full), # NIFTY 50 ] async def on_connect(instance): print("Dhan WebSocket connected") async def on_message(instance, message): print(f"LTP: {message.get('LTP', 'N/A')} | OI: {message.get('OI', 'N/A')}") feed = marketfeed.DhanFeed( client_id = "YOUR_CLIENT_ID", access_token = "YOUR_ACCESS_TOKEN", instruments = instruments, version = "v2", on_connect = on_connect, on_message = on_message ) asyncio.run(feed.connect())

8. Python Code: Upstox API

Python — Upstox Full Setup
"""Upstox API — install: pip install upstox-python-sdk pandas"""
import upstox_client
from upstox_client.rest import ApiException
import pandas as pd
from datetime import date

# Authenticate
configuration = upstox_client.Configuration()
configuration.access_token = "YOUR_ACCESS_TOKEN"  # From OAuth flow

order_api   = upstox_client.OrderApi(upstox_client.ApiClient(configuration))
market_api  = upstox_client.MarketQuoteApi(upstox_client.ApiClient(configuration))
history_api = upstox_client.HistoryApi(upstox_client.ApiClient(configuration))

# Get historical 1-minute candles for NIFTY 50 (up to 2 years free!)
resp = history_api.get_historical_candle_data1(
    instrument_key="NSE_INDEX|Nifty 50",
    interval="1minute",
    to_date=str(date.today()),
    from_date="2026-09-01",
    api_version="2.0"
)
df = pd.DataFrame(
    resp.data.candles,
    columns=["timestamp","open","high","low","close","volume","oi"]
)
print(df.tail())

# Real-time market quote for multiple instruments
quote = market_api.get_market_quote_ohlc(
    instrument_key="NSE_EQ|INE009A01021,NSE_EQ|INE467B01029",  # INFY, WIPRO
    interval="1d",
    api_version="2.0"
)
for sym, data in quote.data.items():
    print(f"{sym}: LTP = {data.last_price}")

# Place a market order
order = upstox_client.PlaceOrderRequest(
    quantity=1,
    product="D",           # D=Delivery, I=Intraday
    validity="DAY",
    price=0,
    instrument_token="NSE_EQ|INE009A01021",  # INFY
    order_type="MARKET",
    transaction_type="BUY",
    disclosed_quantity=0,
    trigger_price=0,
    is_amo=False,
    tag="AlphaStation_algo"
)
response = order_api.place_order(order, api_version="2.0")
print(f"Upstox order: {response.data.order_id}")

Upstox WebSocket Market Data

Python — Upstox WebSocket Feed
"""Upstox Market Data WebSocket — real-time ticks via Protobuf."""
import upstox_client
from upstox_client import MarketDataStreamer

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

def on_open(ws):
    print("Upstox WebSocket opened")

def on_message(ws, data):
    # data is a decoded Protobuf MarketFullFeed message
    for feed in data.feeds.values():
        ltpc = feed.ff.market_ff.ltpc
        print(f"LTP: {ltpc.ltp} | Close: {ltpc.cp}")

def on_error(ws, error):
    print(f"Error: {error}")

streamer = MarketDataStreamer(
    upstox_client.ApiClient(configuration),
    ["NSE_INDEX|Nifty 50", "NSE_EQ|INE009A01021"],  # NIFTY, INFY
    "full"   # "full" = OHLC + depth; "option_greeks" for F&O Greeks
)
streamer.on_open    = on_open
streamer.on_message = on_message
streamer.on_error   = on_error
streamer.connect()

9. Final Verdict

🟠 Dhan DhanHQ API
API Cost10/10
WebSocket Latency9/10
Historical Data6/10
Options / F&O Features10/10
Rate Limits7/10
SDK Quality8/10
Total: 50/60
🟣 Upstox API
API Cost10/10
WebSocket Latency7/10
Historical Data10/10
Options / F&O Features6/10
Rate Limits9/10
SDK Quality9/10
Total: 51/60

🏆 Final Verdict

🟠 Choose Dhan DhanHQ if:
  • You trade NIFTY/BANKNIFTY options primarily
  • You need live Greeks (Delta, Gamma, Theta, Vega)
  • You run multi-leg options strategies (straddles, spreads)
  • You want SPAN margin calculation via API
  • You prefer lower observed WebSocket latency
🟣 Choose Upstox if:
  • You backtest equity intraday strategies (need 2-year 1-min data)
  • You need higher REST API rate limits (25 req/sec)
  • You prefer a clean OpenAPI 3.0 interface
  • You want option Greeks calculated client-side (more flexibility)
  • You prioritize the most polished Python SDK

Related Articles

Frequently Asked Questions

Is Dhan DhanHQ API free?

Yes. Dhan DhanHQ API is completely free with no monthly subscription fee for order placement, real-time WebSocket streaming, options chain data, and historical OHLCV data. Only standard brokerage on executed trades applies.

Is Upstox API free?

Yes. Upstox API is free for all active Upstox account holders. No monthly API subscription fees for historical data (up to 2-year 1-minute candles), real-time WebSocket, or order placement.

Which API has lower WebSocket latency, Dhan or Upstox?

Community benchmarks from Mumbai VPS instances show Dhan DhanHQ WebSocket typically delivers tick data in 5–15ms, while Upstox averages 8–25ms from exchange timestamp. Both are well within acceptable thresholds for most retail algo strategies.

Does Dhan provide options Greeks in the API?

Yes. Dhan’s options chain API returns Delta, Gamma, Theta, Vega, and implied volatility (IV) for each strike. This is a significant advantage over Upstox, which requires traders to compute Greeks client-side using models like Black-Scholes.

What is Upstox’s order limit per day?

Upstox standard accounts are limited to 250 order placements per day. High-frequency or options algo traders may need to contact Upstox support to request a limit increase for their account.