or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

authentication.mdcharges-analytics.mdindex.mdmarket-data.mdorder-management.mdportfolio-management.mdwebsocket-streaming.md
tile.json

tessl/pypi-upstox-python-sdk

The official Python client for communicating with the Upstox API, providing complete trading and investment platform functionality.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/upstox-python-sdk@2.17.x

To install, run

npx @tessl/cli install tessl/pypi-upstox-python-sdk@2.17.0

index.mddocs/

Upstox Python SDK

The official Python client for communicating with the Upstox API, providing complete trading and investment platform functionality. Execute orders in real time, manage user portfolio, stream live market data using WebSocket, and more with comprehensive API coverage.

The Upstox API is a set of REST APIs that provide data required to build complete investment and trading platforms. This SDK is auto-generated from OpenAPI specifications, ensuring consistency and completeness.

Package Information

  • Package Name: upstox-python-sdk
  • Package Type: pypi
  • Language: Python
  • Installation: pip install upstox-python-sdk
  • Version: 2.17.0
  • License: MIT

Core Imports

import upstox_client

Common pattern for API usage:

from upstox_client.api import OrderApi, PortfolioApi, UserApi
from upstox_client import Configuration, ApiClient

Basic Usage

import upstox_client
from upstox_client.api import LoginApi, OrderApi
from upstox_client.models import PlaceOrderRequest

# Configuration
configuration = upstox_client.Configuration()
configuration.access_token = 'YOUR_ACCESS_TOKEN'

# API client
api_client = upstox_client.ApiClient(configuration)

# Get user profile
user_api = upstox_client.UserApi(api_client)
profile_response = user_api.get_profile(api_version='2.0')
print(f"User: {profile_response.data.user_name}")

# Place an order
order_api = upstox_client.OrderApi(api_client)
order_request = PlaceOrderRequest(
    quantity=1,
    product="I",  # Intraday
    validity="DAY",
    price=100.0,
    tag="test_order",
    instrument_token="NSE_EQ|INE002A01018",  # Reliance
    order_type="LIMIT",
    transaction_type="BUY",
    disclosed_quantity=0,
    trigger_price=0,
    is_amo=False
)

order_response = order_api.place_order(order_request, api_version='2.0')
print(f"Order placed: {order_response.data.order_id}")

Architecture

The SDK follows a consistent pattern across all functionality:

  • Configuration: Manages API credentials, endpoints, and client settings
  • ApiClient: Core HTTP client handling authentication and request/response processing
  • API Classes: Specialized classes for different functional areas (orders, portfolio, market data, etc.)
  • Model Classes: Data structures for requests, responses, and domain objects
  • WebSocket Feeders/Streamers: Real-time data streaming with event-driven architecture

The SDK provides both synchronous operations and WebSocket streaming capabilities, supporting complete trading platform development.

Capabilities

Authentication & User Management

Handle OAuth2 authentication flow, user session management, and access user profile and account information.

class LoginApi:
    def authorize(client_id: str, redirect_uri: str, api_version: str, state: str = None, scope: str = None) -> None
    def token(api_version: str, code: str = None, client_id: str = None, client_secret: str = None, redirect_uri: str = None, grant_type: str = None) -> TokenResponse
    def logout(api_version: str) -> LogoutResponse

class UserApi:
    def get_profile(api_version: str) -> GetProfileResponse
    def get_user_fund_margin(api_version: str) -> GetUserFundMarginResponse

Authentication & User Management

Order Management

Complete order lifecycle management including placement, modification, cancellation, and order book access. Supports regular orders, GTT orders, and batch operations.

class OrderApi:
    def place_order(body: PlaceOrderRequest, api_version: str) -> PlaceOrderResponse
    def modify_order(body: ModifyOrderRequest, api_version: str) -> ModifyOrderResponse
    def cancel_order(order_id: str, api_version: str) -> CancelOrderResponse
    def get_order_book(api_version: str) -> GetOrderBookResponse
    def get_trade_history(api_version: str) -> GetTradeResponse

class OrderApiV3:
    def place_gtt_order(body: GttPlaceOrderRequest) -> GttTriggerOrderResponse
    def modify_gtt_order(body: GttModifyOrderRequest) -> GttTriggerOrderResponse
    def cancel_gtt_order(body: GttCancelOrderRequest) -> GttTriggerOrderResponse

Order Management

Market Data & Quotes

Access real-time market quotes, historical data, OHLC candles, option chains, and market status information.

class MarketQuoteApi:
    def ltp(symbol: str, api_version: str) -> GetMarketQuoteLastTradedPriceResponse
    def get_full_market_quote(symbol: str, api_version: str) -> GetFullMarketQuoteResponse
    def get_market_quote_ohlc(symbol: str, interval: str, api_version: str) -> GetMarketQuoteOHLCResponse

class HistoryApi:
    def get_historical_candle_data(instrument_key: str, interval: str, to_date: str, api_version: str) -> GetHistoricalCandleResponse
    def get_intra_day_candle_data(instrument_key: str, interval: str, api_version: str) -> GetIntraDayCandleResponse

class OptionsApi:
    def get_option_contracts(instrument_key: str) -> GetOptionContractResponse
    def get_put_call_option_chain(instrument_key: str, expiry_date: str) -> GetOptionChainResponse

Market Data & Quotes

Portfolio Management

Manage positions, holdings, conversions between product types, and profit & loss analysis.

class PortfolioApi:
    def get_holdings(api_version: str) -> GetHoldingsResponse
    def get_positions(api_version: str) -> GetPositionResponse  
    def convert_positions(body: ConvertPositionRequest, api_version: str) -> ConvertPositionResponse

class TradeProfitAndLossApi:
    def get_profit_and_loss_charges(segment: str, financial_year: str, api_version: str) -> GetProfitAndLossChargesResponse
    def get_trade_wise_profit_and_loss_data(segment: str, financial_year: str, page_number: str, page_size: str, api_version: str) -> GetTradeWiseProfitAndLossDataResponse

Portfolio Management

WebSocket Streaming

Real-time data streaming for market data feeds and portfolio updates using WebSocket connections with event-driven architecture.

class MarketDataStreamer:
    def __init__(api_client: ApiClient = None, instrumentKeys: list = None, mode: str = None)
    def connect() -> None
    def subscribe(instrumentKeys: list, mode: str) -> None
    def unsubscribe(instrumentKeys: list) -> None
    def on(event: str, listener: callable) -> None

class PortfolioDataStreamer:
    def __init__(api_client: ApiClient = None, order_update: bool = None, position_update: bool = None, holding_update: bool = None, gtt_update: bool = None)
    def connect() -> None
    def on(event: str, listener: callable) -> None

WebSocket Streaming

Charges & Analytics

Calculate brokerage charges, required margins, market timings, and holidays information.

class ChargeApi:
    def get_brokerage(instrument_token: str, quantity: int, product: str, transaction_type: str, price: float, api_version: str) -> GetBrokerageResponse
    def post_margin(body: MarginRequest) -> PostMarginResponse

class MarketHolidaysAndTimingsApi:
    def get_market_status(exchange: str) -> GetMarketStatusResponse
    def get_exchange_timings(date: str) -> GetExchangeTimingResponse
    def get_holidays() -> GetHolidayResponse

Charges & Analytics

Common Types

class Configuration:
    def __init__(sandbox: bool = False) -> None
    access_token: str
    api_key: dict
    debug: bool
    
class ApiClient:
    def __init__(configuration: Configuration = None) -> None
    def call_api(resource_path: str, method: str, **kwargs) -> object
    def set_default_header(header_name: str, header_value: str) -> None

# Request Models
class PlaceOrderRequest:
    quantity: int
    product: str  # 'I' (Intraday), 'D' (Delivery), 'M' (Margin)
    validity: str  # 'DAY', 'IOC' 
    price: float
    tag: str
    instrument_token: str  # Format: "EXCHANGE_SEGMENT|TOKEN"
    order_type: str  # 'MARKET', 'LIMIT', 'SL', 'SL-M'
    transaction_type: str  # 'BUY', 'SELL'
    disclosed_quantity: int
    trigger_price: float
    is_amo: bool  # After Market Order

class ModifyOrderRequest:
    quantity: int
    validity: str
    price: float
    order_id: str
    order_type: str
    disclosed_quantity: int
    trigger_price: float

class ConvertPositionRequest:
    instrument_token: str
    new_product: str
    old_product: str  
    transaction_type: str
    quantity: int

# Response Models  
class GetProfileResponse:
    status: str
    data: ProfileData

class GetOrderBookResponse:
    status: str
    data: list[OrderBookData]

class GetPositionResponse:
    status: str
    data: list[PositionData]

class GetHoldingsResponse:
    status: str  
    data: list[HoldingsData]

# Data Models
class ProfileData:
    user_id: str
    user_name: str
    user_type: str
    poa: bool
    is_active: bool
    broker: str
    exchanges: list[str]
    products: list[str]
    
class OrderBookData:
    order_id: str
    exchange: str
    instrument_token: str
    product: str
    order_type: str
    transaction_type: str
    quantity: int
    price: float
    status: str
    
class PositionData:
    exchange: str
    instrument_token: str
    product: str
    quantity: int
    buy_price: float
    sell_price: float
    pnl: float
    
class HoldingsData:
    instrument_token: str
    exchange: str
    tradingsymbol: str
    quantity: int
    t1_quantity: int
    average_price: float
    last_price: float
    pnl: float