The official Python client for communicating with the Upstox API, providing complete trading and investment platform functionality.
Access real-time market quotes, historical data, OHLC candles, option chains, market status information, and expired instrument data.
Get current market prices, depth, and comprehensive quote information.
def ltp(symbol: str, api_version: str) -> GetMarketQuoteLastTradedPriceResponse:
"""
Get Last Traded Price for instruments.
Parameters:
- symbol: Comma-separated instrument tokens
- api_version: API version ('2.0')
Returns:
GetMarketQuoteLastTradedPriceResponse with LTP data
"""
def get_full_market_quote(symbol: str, api_version: str) -> GetFullMarketQuoteResponse:
"""
Get complete market quote with depth, OHLC, and other details.
Parameters:
- symbol: Comma-separated instrument tokens
- api_version: API version ('2.0')
Returns:
GetFullMarketQuoteResponse with comprehensive quote data
"""
def get_market_quote_ohlc(symbol: str, interval: str, api_version: str) -> GetMarketQuoteOHLCResponse:
"""
Get OHLC (Open, High, Low, Close) data for instruments.
Parameters:
- symbol: Comma-separated instrument tokens
- interval: Time interval ('1m', '3m', '5m', '15m', '30m', '1h', '1d')
- api_version: API version ('2.0')
Returns:
GetMarketQuoteOHLCResponse with OHLC data
"""from upstox_client.api import MarketQuoteApi
from upstox_client import Configuration, ApiClient
# Setup
config = Configuration()
config.access_token = 'your_access_token'
api_client = ApiClient(config)
quote_api = MarketQuoteApi(api_client)
# Get Last Traded Price
instruments = "NSE_EQ|INE002A01018,NSE_EQ|INE009A01021" # Reliance, Infosys
ltp_response = quote_api.ltp(instruments, api_version='2.0')
for symbol, data in ltp_response.data.items():
print(f"{symbol}: ₹{data.last_price}")
# Get full market quote with depth
full_quote = quote_api.get_full_market_quote(
"NSE_EQ|INE002A01018",
api_version='2.0'
)
quote_data = full_quote.data["NSE_EQ|INE002A01018"]
print(f"LTP: ₹{quote_data.last_price}")
print(f"Volume: {quote_data.volume}")
print(f"Change: {quote_data.net_change} ({quote_data.percent_change}%)")
# Market depth
depth = quote_data.depth
print("Buy Orders:")
for buy_order in depth.buy:
print(f" Price: ₹{buy_order.price}, Quantity: {buy_order.quantity}")
print("Sell Orders:")
for sell_order in depth.sell:
print(f" Price: ₹{sell_order.price}, Quantity: {sell_order.quantity}")
# Get OHLC data
ohlc_response = quote_api.get_market_quote_ohlc(
"NSE_EQ|INE002A01018",
interval='1d',
api_version='2.0'
)
ohlc_data = ohlc_response.data["NSE_EQ|INE002A01018"]
print(f"Open: ₹{ohlc_data.ohlc.open}")
print(f"High: ₹{ohlc_data.ohlc.high}")
print(f"Low: ₹{ohlc_data.ohlc.low}")
print(f"Close: ₹{ohlc_data.ohlc.close}")Improved market quote API with batch support and option Greeks.
def get_ltp(instrument_key: str = None) -> GetMarketQuoteLastTradedPriceResponseV3:
"""
Get Last Traded Price for multiple instruments (V3).
Parameters:
- instrument_key: Comma-separated list of instrument keys (optional, up to 500)
Returns:
GetMarketQuoteLastTradedPriceResponseV3 with LTP data
"""
def get_market_quote_ohlc(interval: str, instrument_key: str = None) -> GetMarketQuoteOHLCResponseV3:
"""
Get OHLC data for instruments (V3).
Parameters:
- interval: Time interval for OHLC data (required)
- instrument_key: Comma-separated list of instrument keys (optional, up to 500)
Returns:
GetMarketQuoteOHLCResponseV3 with OHLC data
"""
def get_market_quote_option_greek(instrument_key: str = None) -> GetMarketQuoteOptionGreekResponseV3:
"""
Get option Greeks (Delta, Gamma, Theta, Vega) for option instruments.
Parameters:
- instrument_key: Comma-separated list of instrument keys (optional, up to 500)
Returns:
GetMarketQuoteOptionGreekResponseV3 with Greeks data
"""Retrieve historical OHLC candle data and intraday data.
def get_historical_candle_data(instrument_key: str, interval: str, to_date: str, api_version: str) -> GetHistoricalCandleResponse:
"""
Get historical candle data for an instrument.
Parameters:
- instrument_key: Instrument identifier
- interval: Candle interval ('minute', 'day', 'week', 'month')
- to_date: End date in YYYY-MM-DD format
- api_version: API version ('2.0')
Returns:
GetHistoricalCandleResponse with historical candles
"""
def get_historical_candle_data1(instrument_key: str, interval: str, to_date: str, from_date: str, api_version: str) -> GetHistoricalCandleResponse:
"""
Get historical candle data for a date range.
Parameters:
- instrument_key: Instrument identifier
- interval: Candle interval
- to_date: End date in YYYY-MM-DD format
- from_date: Start date in YYYY-MM-DD format
- api_version: API version ('2.0')
Returns:
GetHistoricalCandleResponse with historical candles
"""
def get_intra_day_candle_data(instrument_key: str, interval: str, api_version: str) -> GetIntraDayCandleResponse:
"""
Get intraday candle data for current trading day.
Parameters:
- instrument_key: Instrument identifier
- interval: Candle interval ('1minute', '30minute')
- api_version: API version ('2.0')
Returns:
GetIntraDayCandleResponse with intraday candles
"""from upstox_client.api import HistoryApi
history_api = HistoryApi(api_client)
# Get historical daily candles
historical_data = history_api.get_historical_candle_data(
instrument_key="NSE_EQ|INE002A01018",
interval="day",
to_date="2024-09-06",
api_version='2.0'
)
print("Historical Daily Data:")
for candle in historical_data.data.candles:
timestamp, open_price, high, low, close, volume, oi = candle
print(f"Date: {timestamp}, OHLC: {open_price}/{high}/{low}/{close}, Volume: {volume}")
# Get historical data with date range
range_data = history_api.get_historical_candle_data1(
instrument_key="NSE_EQ|INE002A01018",
interval="day",
to_date="2024-09-06",
from_date="2024-08-01",
api_version='2.0'
)
# Get intraday data
intraday_data = history_api.get_intra_day_candle_data(
instrument_key="NSE_EQ|INE002A01018",
interval="30minute",
api_version='2.0'
)
print("Intraday 30-minute Data:")
for candle in intraday_data.data.candles:
timestamp, open_price, high, low, close, volume, oi = candle
print(f"Time: {timestamp}, OHLC: {open_price}/{high}/{low}/{close}")Extended historical data API with flexible time units and intervals.
def get_historical_candle_data(instrument_key: str, unit: str, interval: int, to_date: str) -> GetHistoricalCandleResponse:
"""
Get historical candle data with flexible time units (V3).
Parameters:
- instrument_key: Instrument identifier (required)
- unit: Time unit ('minute', 'day', 'week', 'month') (required)
- interval: Interval number (e.g., 1, 5, 15, 30) (required)
- to_date: End date in YYYY-MM-DD format (required)
Returns:
GetHistoricalCandleResponse with historical candles
"""
def get_historical_candle_data1(instrument_key: str, unit: str, interval: int, to_date: str, from_date: str) -> GetHistoricalCandleResponse:
"""
Get historical candle data with date range and flexible intervals (V3).
Parameters:
- instrument_key: Instrument identifier (required)
- unit: Time unit ('minute', 'day', 'week', 'month') (required)
- interval: Interval number (e.g., 1, 5, 15, 30) (required)
- to_date: End date in YYYY-MM-DD format (required)
- from_date: Start date in YYYY-MM-DD format (required)
Returns:
GetHistoricalCandleResponse with historical candles
"""
def get_intra_day_candle_data(instrument_key: str, unit: str, interval: int) -> GetIntraDayCandleResponse:
"""
Get intraday candle data with flexible intervals (V3).
Parameters:
- instrument_key: Instrument identifier (required)
- unit: Time unit ('minute') (required)
- interval: Interval in minutes (1, 5, 15, 30) (required)
Returns:
GetIntraDayCandleResponse with intraday candles
"""Access option contracts, option chains, and option-specific market data.
def get_option_contracts(instrument_key: str) -> GetOptionContractResponse:
"""
Get available option contracts for an underlying instrument.
Parameters:
- instrument_key: Underlying instrument identifier
Returns:
GetOptionContractResponse with option contracts
"""
def get_put_call_option_chain(instrument_key: str, expiry_date: str) -> GetOptionChainResponse:
"""
Get complete option chain with put and call options.
Parameters:
- instrument_key: Underlying instrument identifier
- expiry_date: Option expiry date in YYYY-MM-DD format
Returns:
GetOptionChainResponse with option chain data
"""from upstox_client.api import OptionsApi
options_api = OptionsApi(api_client)
# Get option contracts for Nifty
option_contracts = options_api.get_option_contracts("NSE_INDEX|Nifty 50")
print("Available Expiry Dates:")
for expiry in option_contracts.data:
print(f"Expiry: {expiry}")
# Get option chain for specific expiry
option_chain = options_api.get_put_call_option_chain(
instrument_key="NSE_INDEX|Nifty 50",
expiry_date="2024-09-26"
)
print("Option Chain:")
for strike_price, strike_data in option_chain.data.items():
call_data = strike_data.call_options
put_data = strike_data.put_options
print(f"Strike {strike_price}:")
if call_data:
print(f" Call LTP: ₹{call_data.last_price}, IV: {call_data.implied_volatility}")
if put_data:
print(f" Put LTP: ₹{put_data.last_price}, IV: {put_data.implied_volatility}")Get market timings, holidays, and exchange status information.
def get_market_status(exchange: str) -> GetMarketStatusResponse:
"""
Get current market status for an exchange.
Parameters:
- exchange: Exchange name ('NSE', 'BSE', 'MCX')
Returns:
GetMarketStatusResponse with market status
"""
def get_exchange_timings(date: str) -> GetExchangeTimingResponse:
"""
Get exchange trading timings for a specific date.
Parameters:
- date: Date in YYYY-MM-DD format
Returns:
GetExchangeTimingResponse with trading hours
"""
def get_holidays() -> GetHolidayResponse:
"""
Get list of market holidays.
Returns:
GetHolidayResponse with holiday information
"""
def get_holiday(date: str) -> GetHolidayResponse:
"""
Check if a specific date is a market holiday.
Parameters:
- date: Date in YYYY-MM-DD format
Returns:
GetHolidayResponse with holiday status
"""Access expired futures and options contracts and their historical data.
def get_expired_future_contracts(instrument_key: str, expiry_date: str) -> GetExpiredFuturesContractResponse:
"""
Get expired futures contracts.
Parameters:
- instrument_key: Underlying instrument identifier
- expiry_date: Expiry date in YYYY-MM-DD format
Returns:
GetExpiredFuturesContractResponse with expired contracts
"""
def get_expired_option_contracts(instrument_key: str, expiry_date: str) -> GetOptionContractResponse:
"""
Get expired option contracts.
Parameters:
- instrument_key: Underlying instrument identifier
- expiry_date: Expiry date in YYYY-MM-DD format
Returns:
GetOptionContractResponse with expired option contracts
"""
def get_expired_historical_candle_data(expired_instrument_key: str, interval: str, to_date: str, from_date: str) -> GetHistoricalCandleResponse:
"""
Get historical data for expired instruments.
Parameters:
- expired_instrument_key: Expired instrument identifier
- interval: Candle interval
- to_date: End date in YYYY-MM-DD format
- from_date: Start date in YYYY-MM-DD format
Returns:
GetHistoricalCandleResponse with historical data
"""
def get_expiries(instrument_key: str) -> GetExpiriesResponse:
"""
Get available expiry dates for an instrument.
Parameters:
- instrument_key: Instrument identifier
Returns:
GetExpiriesResponse with expiry dates
"""class GetMarketQuoteLastTradedPriceResponse:
status: str
data: dict[str, MarketQuoteSymbolLtp]
class MarketQuoteSymbolLtp:
instrument_token: str
last_price: float
class GetFullMarketQuoteResponse:
status: str
data: dict[str, MarketQuoteSymbol]
class MarketQuoteSymbol:
instrument_token: str
exchange: str
tradingsymbol: str
last_price: float
previous_close: float
change: float
percent_change: float
volume: int
last_trade_time: str
oi: int # Open Interest
oi_day_high: int
oi_day_low: int
depth: Depth # Market depth
class Depth:
buy: list[DepthItem]
sell: list[DepthItem]
class DepthItem:
price: float
quantity: int
orders: int
class GetMarketQuoteOHLCResponse:
status: str
data: dict[str, MarketQuoteOHLC]
class MarketQuoteOHLC:
instrument_token: str
ohlc: Ohlc
class Ohlc:
open: float
high: float
low: float
close: float
class GetHistoricalCandleResponse:
status: str
data: HistoricalCandleData
class HistoricalCandleData:
candles: list[list] # Each candle: [timestamp, open, high, low, close, volume, oi]
class GetIntraDayCandleResponse:
status: str
data: IntraDayCandleData
class IntraDayCandleData:
candles: list[list] # Each candle: [timestamp, open, high, low, close, volume, oi]
class GetOptionChainResponse:
status: str
data: dict[str, PutCallOptionChainData]
class PutCallOptionChainData:
strike_price: float
call_options: OptionStrikeData
put_options: OptionStrikeData
class OptionStrikeData:
instrument_token: str
last_price: float
implied_volatility: float
delta: float
gamma: float
theta: float
vega: float
class GetMarketStatusResponse:
status: str
data: list[MarketStatusData]
class MarketStatusData:
exchange: str
status: str # 'open', 'close', 'break'
class GetExchangeTimingResponse:
status: str
data: list[ExchangeTimingData]
class ExchangeTimingData:
exchange: str
trading_start_time: str
trading_end_time: str
class GetHolidayResponse:
status: str
data: list[HolidayData]
class HolidayData:
date: str
description: str
holiday_type: strInstrument tokens identify specific tradeable instruments:
"NSE_EQ|INE002A01018" - Reliance Industries (NSE)"BSE_EQ|INE002A01018" - Reliance Industries (BSE)"NSE_INDEX|Nifty 50" - Nifty 50 Index"NSE_INDEX|Nifty Bank" - Bank Nifty Index"NSE_FO|46942" - Futures contract on NSE"MCX_FO|249736" - Commodity futures on MCX"NSE_FO|46943" - Options contract on NSE"NSE_CD|1" - Currency derivativesUse the instrument master files or search APIs to get exact instrument tokens for your trading needs.
Install with Tessl CLI
npx tessl i tessl/pypi-upstox-python-sdk