The official Python client for communicating with the Upstox API, providing complete trading and investment platform functionality.
Complete order lifecycle management including placement, modification, cancellation, order book access, and trade history. Supports regular orders, GTT (Good Till Triggered) orders, and batch operations.
Place various types of trading orders with comprehensive parameter support.
def place_order(body: PlaceOrderRequest, api_version: str) -> PlaceOrderResponse:
"""
Place a new trading order.
Parameters:
- body: Order details and parameters
- api_version: API version ('2.0')
Returns:
PlaceOrderResponse with order_id and status
"""
def place_multi_order(body: MultiOrderRequest) -> MultiOrderResponse:
"""
Place multiple orders in a single batch request.
Parameters:
- body: List of order requests
Returns:
MultiOrderResponse with individual order results
"""from upstox_client.api import OrderApi
from upstox_client.models import PlaceOrderRequest
from upstox_client import Configuration, ApiClient
# Setup
config = Configuration()
config.access_token = 'your_access_token'
api_client = ApiClient(config)
order_api = OrderApi(api_client)
# Place a limit order
order_request = PlaceOrderRequest(
quantity=10,
product="I", # Intraday
validity="DAY",
price=1500.0,
tag="my_order_tag",
instrument_token="NSE_EQ|INE002A01018", # Reliance Industries
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')
order_id = order_response.data.order_id
print(f"Order placed successfully. Order ID: {order_id}")
# Place a market order
market_order = PlaceOrderRequest(
quantity=5,
product="D", # Delivery
validity="DAY",
price=0, # Not needed for market orders
tag="market_buy",
instrument_token="NSE_EQ|INE009A01021", # Infosys
order_type="MARKET",
transaction_type="BUY",
disclosed_quantity=0,
trigger_price=0,
is_amo=False
)
market_response = order_api.place_order(market_order, api_version='2.0')Modify existing orders with updated parameters.
def modify_order(body: ModifyOrderRequest, api_version: str) -> ModifyOrderResponse:
"""
Modify an existing order.
Parameters:
- body: Modified order parameters
- api_version: API version ('2.0')
Returns:
ModifyOrderResponse with updated order details
"""from upstox_client.models import ModifyOrderRequest
# Modify order price and quantity
modify_request = ModifyOrderRequest(
quantity=15, # New quantity
validity="DAY",
price=1520.0, # New price
order_id="240906000000123", # Order ID to modify
order_type="LIMIT",
disclosed_quantity=0,
trigger_price=0
)
modify_response = order_api.modify_order(modify_request, api_version='2.0')
print(f"Order modified: {modify_response.data.order_id}")Cancel individual orders or multiple orders in batch.
def cancel_order(order_id: str, api_version: str) -> CancelOrderResponse:
"""
Cancel a specific order.
Parameters:
- order_id: ID of order to cancel
- api_version: API version ('2.0')
Returns:
CancelOrderResponse with cancellation status
"""
def cancel_multi_order() -> CancelOrExitMultiOrderResponse:
"""
Cancel multiple orders in batch.
Returns:
CancelOrExitMultiOrderResponse with batch operation results
"""
def exit_positions() -> CancelOrExitMultiOrderResponse:
"""
Exit all open positions by placing opposite orders.
Returns:
CancelOrExitMultiOrderResponse with exit operation results
"""# Cancel specific order
cancel_response = order_api.cancel_order(
order_id="240906000000123",
api_version='2.0'
)
print(f"Order cancelled: {cancel_response.data.order_id}")
# Exit all positions
exit_response = order_api.exit_positions()
print(f"Positions exited: {len(exit_response.data)} operations")Access order book, order details, and trade execution history.
def get_order_book(api_version: str) -> GetOrderBookResponse:
"""
Retrieve all orders for the trading day.
Parameters:
- api_version: API version ('2.0')
Returns:
GetOrderBookResponse with list of orders
"""
def get_order_details(api_version: str) -> GetOrderDetailsResponse:
"""
Get detailed information about orders.
Parameters:
- api_version: API version ('2.0')
Returns:
GetOrderDetailsResponse with comprehensive order data
"""
def get_trade_history(api_version: str) -> GetTradeResponse:
"""
Retrieve trade execution history.
Parameters:
- api_version: API version ('2.0')
Returns:
GetTradeResponse with executed trades
"""
def get_trades_by_order(order_id: str, api_version: str) -> GetTradeResponse:
"""
Get all trades for a specific order.
Parameters:
- order_id: Order ID to get trades for
- api_version: API version ('2.0')
Returns:
GetTradeResponse with trades for the order
"""# Get all orders
order_book = order_api.get_order_book(api_version='2.0')
for order in order_book.data:
print(f"Order {order.order_id}: {order.status} - {order.tradingsymbol}")
# Get trade history
trades = order_api.get_trade_history(api_version='2.0')
for trade in trades.data:
print(f"Trade: {trade.tradingsymbol} - {trade.quantity} @ {trade.price}")Advanced order management with improved performance and features.
def place_order(body: PlaceOrderV3Request, origin: str = None) -> PlaceOrderV3Response:
"""
Place a new trading order using V3 API.
Parameters:
- body: Order details and parameters (required)
- origin: Order origin identifier (optional)
Returns:
PlaceOrderV3Response with order placement result
"""
def modify_order(body: ModifyOrderRequest, origin: str = None) -> ModifyOrderV3Response:
"""
Modify an existing order using V3 API.
Parameters:
- body: Order modification parameters (required)
- origin: Order origin identifier (optional)
Returns:
ModifyOrderV3Response with modification result
"""
def cancel_order(order_id: str, origin: str = None) -> CancelOrderV3Response:
"""
Cancel an existing order using V3 API.
Parameters:
- order_id: Unique identifier of the order to cancel (required)
- origin: Order origin identifier (optional)
Returns:
CancelOrderV3Response with cancellation result
"""from upstox_client.api import OrderApiV3
from upstox_client.models import PlaceOrderV3Request
# V3 API for enhanced order management
order_api_v3 = OrderApiV3(api_client)
# Place order using V3 API
order_request_v3 = PlaceOrderV3Request(
quantity=100,
product="D",
validity="DAY",
price=1500.0,
tag="v3_order",
instrument_token="NSE_EQ|INE002A01018",
order_type="LIMIT",
transaction_type="BUY",
disclosed_quantity=0,
trigger_price=0.0,
is_amo=False
)
order_response_v3 = order_api_v3.place_order(order_request_v3)
print(f"V3 Order placed: {order_response_v3.data.order_id}")
# Cancel order using V3 API
cancel_response_v3 = order_api_v3.cancel_order(order_response_v3.data.order_id)
print(f"Order cancelled: {cancel_response_v3.status}")Advanced order types that remain active until triggered by market conditions.
def place_gtt_order(body: GttPlaceOrderRequest) -> GttTriggerOrderResponse:
"""
Place a GTT (Good Till Triggered) order.
Parameters:
- body: GTT order parameters with trigger conditions
Returns:
GttTriggerOrderResponse with GTT order details
"""
def modify_gtt_order(body: GttModifyOrderRequest) -> GttTriggerOrderResponse:
"""
Modify an existing GTT order.
Parameters:
- body: Updated GTT order parameters
Returns:
GttTriggerOrderResponse with modified GTT details
"""
def cancel_gtt_order(body: GttCancelOrderRequest) -> GttTriggerOrderResponse:
"""
Cancel a GTT order.
Parameters:
- body: GTT cancellation request
Returns:
GttTriggerOrderResponse confirming cancellation
"""
def get_gtt_order_details() -> GetGttOrderResponse:
"""
Get details of all GTT orders.
Returns:
GetGttOrderResponse with GTT order information
"""from upstox_client.api import OrderApiV3
from upstox_client.models import GttPlaceOrderRequest, GttRule
# V3 API for GTT orders
order_api_v3 = OrderApiV3(api_client)
# Create GTT rule
gtt_rule = GttRule(
instrument_token="NSE_EQ|INE002A01018",
trigger_type="single", # or 'ocp' for OCO-Plus
trigger_values=[1600.0], # Trigger price
exchange="NSE"
)
# Place GTT order
gtt_request = GttPlaceOrderRequest(
rules=[gtt_rule],
quantity=10,
price=1605.0,
product="D",
validity="GTT",
order_type="LIMIT",
transaction_type="SELL"
)
gtt_response = order_api_v3.place_gtt_order(gtt_request)
print(f"GTT Order placed: {gtt_response.data.gtt_order_id}")
# Get GTT order details
gtt_details = order_api_v3.get_gtt_order_details()
for gtt_order in gtt_details.data:
print(f"GTT Order: {gtt_order.id} - Status: {gtt_order.status}")class PlaceOrderRequest:
quantity: int # Number of shares/units
product: str # 'I' (Intraday), 'D' (Delivery), 'M' (Margin), 'CO' (Cover Order), 'BO' (Bracket Order)
validity: str # 'DAY', 'IOC' (Immediate or Cancel), 'GTT' (Good Till Triggered)
price: float # Order price (0 for market orders)
tag: str # Custom tag for order identification
instrument_token: str # Format: "EXCHANGE_SEGMENT|TOKEN" (e.g., "NSE_EQ|INE002A01018")
order_type: str # 'MARKET', 'LIMIT', 'SL' (Stop Loss), 'SL-M' (Stop Loss Market)
transaction_type: str # 'BUY', 'SELL'
disclosed_quantity: int # Quantity to disclose (0 for full disclosure)
trigger_price: float # Trigger price for SL orders (0 if not applicable)
is_amo: bool # After Market Order flag
class ModifyOrderRequest:
quantity: int
validity: str
price: float
order_id: str # Order ID to modify
order_type: str
disclosed_quantity: int
trigger_price: float
class MultiOrderRequest:
orders: list[PlaceOrderRequest] # List of orders to place
class GttPlaceOrderRequest:
rules: list[GttRule] # GTT trigger rules
quantity: int
price: float
product: str
validity: str
order_type: str
transaction_type: str
class GttRule:
instrument_token: str
trigger_type: str # 'single', 'ocp' (OCO-Plus)
trigger_values: list[float] # Trigger prices
exchange: str
class PlaceOrderResponse:
status: str
data: PlaceOrderData
class PlaceOrderData:
order_id: str # Unique order identifier
class GetOrderBookResponse:
status: str
data: list[OrderBookData]
class OrderBookData:
order_id: str
exchange: str
instrument_token: str
tradingsymbol: str # Trading symbol (e.g., "RELIANCE")
product: str
order_type: str
transaction_type: str
quantity: int
price: float
trigger_price: float
disclosed_quantity: int
validity: str
status: str # 'open', 'complete', 'cancelled', 'rejected', 'modify_pending'
tag: str
filled_quantity: int
pending_quantity: int
average_price: float
order_timestamp: str
exchange_order_id: str
parent_order_id: str
class GetTradeResponse:
status: str
data: list[TradeData]
class TradeData:
exchange: str
instrument_token: str
tradingsymbol: str
order_id: str
exchange_order_id: str
trade_id: str
transaction_type: str
quantity: int
price: float
trade_timestamp: str
class GttTriggerOrderResponse:
status: str
data: GttOrderData
class GttOrderData:
gtt_order_id: str
trigger_id: str
status: str"I" - Intraday: Square off before market close"D" - Delivery: Hold for delivery"M" - Margin: Margin trading"CO" - Cover Order: Intraday with compulsory stop loss"BO" - Bracket Order: Intraday with target and stop loss"MARKET" - Execute at best available price"LIMIT" - Execute at specified price or better"SL" - Stop Loss: Trigger when price reaches trigger_price"SL-M" - Stop Loss Market: Market order when triggered"DAY" - Valid for the trading day"IOC" - Immediate or Cancel"GTT" - Good Till Triggered (for GTT orders)Format: "EXCHANGE_SEGMENT|TOKEN"
Examples:
"NSE_EQ|INE002A01018" - Reliance Industries on NSE Equity"BSE_EQ|INE002A01018" - Reliance Industries on BSE Equity"NSE_FO|46942" - Futures/Options on NSE"MCX_FO|249736" - Commodity futures on MCXfrom upstox_client.rest import ApiException
try:
order_response = order_api.place_order(order_request, api_version='2.0')
except ApiException as e:
print(f"Order placement failed: {e.status} - {e.reason}")
# Handle different error scenarios
if e.status == 400:
print("Invalid order parameters")
elif e.status == 403:
print("Insufficient permissions or margin")
elif e.status == 429:
print("Rate limit exceeded")Common order errors:
400 Bad Request: Invalid order parameters403 Forbidden: Insufficient margin or permissions422 Unprocessable Entity: Business rule violations429 Too Many Requests: Rate limit exceededInstall with Tessl CLI
npx tessl i tessl/pypi-upstox-python-sdk