The official Python client for communicating with the Upstox API, providing complete trading and investment platform functionality.
npx @tessl/cli install tessl/pypi-upstox-python-sdk@2.17.00
# Upstox Python SDK
1
2
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.
3
4
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.
5
6
## Package Information
7
8
- **Package Name**: upstox-python-sdk
9
- **Package Type**: pypi
10
- **Language**: Python
11
- **Installation**: `pip install upstox-python-sdk`
12
- **Version**: 2.17.0
13
- **License**: MIT
14
15
## Core Imports
16
17
```python
18
import upstox_client
19
```
20
21
Common pattern for API usage:
22
23
```python
24
from upstox_client.api import OrderApi, PortfolioApi, UserApi
25
from upstox_client import Configuration, ApiClient
26
```
27
28
## Basic Usage
29
30
```python
31
import upstox_client
32
from upstox_client.api import LoginApi, OrderApi
33
from upstox_client.models import PlaceOrderRequest
34
35
# Configuration
36
configuration = upstox_client.Configuration()
37
configuration.access_token = 'YOUR_ACCESS_TOKEN'
38
39
# API client
40
api_client = upstox_client.ApiClient(configuration)
41
42
# Get user profile
43
user_api = upstox_client.UserApi(api_client)
44
profile_response = user_api.get_profile(api_version='2.0')
45
print(f"User: {profile_response.data.user_name}")
46
47
# Place an order
48
order_api = upstox_client.OrderApi(api_client)
49
order_request = PlaceOrderRequest(
50
quantity=1,
51
product="I", # Intraday
52
validity="DAY",
53
price=100.0,
54
tag="test_order",
55
instrument_token="NSE_EQ|INE002A01018", # Reliance
56
order_type="LIMIT",
57
transaction_type="BUY",
58
disclosed_quantity=0,
59
trigger_price=0,
60
is_amo=False
61
)
62
63
order_response = order_api.place_order(order_request, api_version='2.0')
64
print(f"Order placed: {order_response.data.order_id}")
65
```
66
67
## Architecture
68
69
The SDK follows a consistent pattern across all functionality:
70
71
- **Configuration**: Manages API credentials, endpoints, and client settings
72
- **ApiClient**: Core HTTP client handling authentication and request/response processing
73
- **API Classes**: Specialized classes for different functional areas (orders, portfolio, market data, etc.)
74
- **Model Classes**: Data structures for requests, responses, and domain objects
75
- **WebSocket Feeders/Streamers**: Real-time data streaming with event-driven architecture
76
77
The SDK provides both synchronous operations and WebSocket streaming capabilities, supporting complete trading platform development.
78
79
## Capabilities
80
81
### Authentication & User Management
82
83
Handle OAuth2 authentication flow, user session management, and access user profile and account information.
84
85
```python { .api }
86
class LoginApi:
87
def authorize(client_id: str, redirect_uri: str, api_version: str, state: str = None, scope: str = None) -> None
88
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
89
def logout(api_version: str) -> LogoutResponse
90
91
class UserApi:
92
def get_profile(api_version: str) -> GetProfileResponse
93
def get_user_fund_margin(api_version: str) -> GetUserFundMarginResponse
94
```
95
96
[Authentication & User Management](./authentication.md)
97
98
### Order Management
99
100
Complete order lifecycle management including placement, modification, cancellation, and order book access. Supports regular orders, GTT orders, and batch operations.
101
102
```python { .api }
103
class OrderApi:
104
def place_order(body: PlaceOrderRequest, api_version: str) -> PlaceOrderResponse
105
def modify_order(body: ModifyOrderRequest, api_version: str) -> ModifyOrderResponse
106
def cancel_order(order_id: str, api_version: str) -> CancelOrderResponse
107
def get_order_book(api_version: str) -> GetOrderBookResponse
108
def get_trade_history(api_version: str) -> GetTradeResponse
109
110
class OrderApiV3:
111
def place_gtt_order(body: GttPlaceOrderRequest) -> GttTriggerOrderResponse
112
def modify_gtt_order(body: GttModifyOrderRequest) -> GttTriggerOrderResponse
113
def cancel_gtt_order(body: GttCancelOrderRequest) -> GttTriggerOrderResponse
114
```
115
116
[Order Management](./order-management.md)
117
118
### Market Data & Quotes
119
120
Access real-time market quotes, historical data, OHLC candles, option chains, and market status information.
121
122
```python { .api }
123
class MarketQuoteApi:
124
def ltp(symbol: str, api_version: str) -> GetMarketQuoteLastTradedPriceResponse
125
def get_full_market_quote(symbol: str, api_version: str) -> GetFullMarketQuoteResponse
126
def get_market_quote_ohlc(symbol: str, interval: str, api_version: str) -> GetMarketQuoteOHLCResponse
127
128
class HistoryApi:
129
def get_historical_candle_data(instrument_key: str, interval: str, to_date: str, api_version: str) -> GetHistoricalCandleResponse
130
def get_intra_day_candle_data(instrument_key: str, interval: str, api_version: str) -> GetIntraDayCandleResponse
131
132
class OptionsApi:
133
def get_option_contracts(instrument_key: str) -> GetOptionContractResponse
134
def get_put_call_option_chain(instrument_key: str, expiry_date: str) -> GetOptionChainResponse
135
```
136
137
[Market Data & Quotes](./market-data.md)
138
139
### Portfolio Management
140
141
Manage positions, holdings, conversions between product types, and profit & loss analysis.
142
143
```python { .api }
144
class PortfolioApi:
145
def get_holdings(api_version: str) -> GetHoldingsResponse
146
def get_positions(api_version: str) -> GetPositionResponse
147
def convert_positions(body: ConvertPositionRequest, api_version: str) -> ConvertPositionResponse
148
149
class TradeProfitAndLossApi:
150
def get_profit_and_loss_charges(segment: str, financial_year: str, api_version: str) -> GetProfitAndLossChargesResponse
151
def get_trade_wise_profit_and_loss_data(segment: str, financial_year: str, page_number: str, page_size: str, api_version: str) -> GetTradeWiseProfitAndLossDataResponse
152
```
153
154
[Portfolio Management](./portfolio-management.md)
155
156
### WebSocket Streaming
157
158
Real-time data streaming for market data feeds and portfolio updates using WebSocket connections with event-driven architecture.
159
160
```python { .api }
161
class MarketDataStreamer:
162
def __init__(api_client: ApiClient = None, instrumentKeys: list = None, mode: str = None)
163
def connect() -> None
164
def subscribe(instrumentKeys: list, mode: str) -> None
165
def unsubscribe(instrumentKeys: list) -> None
166
def on(event: str, listener: callable) -> None
167
168
class PortfolioDataStreamer:
169
def __init__(api_client: ApiClient = None, order_update: bool = None, position_update: bool = None, holding_update: bool = None, gtt_update: bool = None)
170
def connect() -> None
171
def on(event: str, listener: callable) -> None
172
```
173
174
[WebSocket Streaming](./websocket-streaming.md)
175
176
### Charges & Analytics
177
178
Calculate brokerage charges, required margins, market timings, and holidays information.
179
180
```python { .api }
181
class ChargeApi:
182
def get_brokerage(instrument_token: str, quantity: int, product: str, transaction_type: str, price: float, api_version: str) -> GetBrokerageResponse
183
def post_margin(body: MarginRequest) -> PostMarginResponse
184
185
class MarketHolidaysAndTimingsApi:
186
def get_market_status(exchange: str) -> GetMarketStatusResponse
187
def get_exchange_timings(date: str) -> GetExchangeTimingResponse
188
def get_holidays() -> GetHolidayResponse
189
```
190
191
[Charges & Analytics](./charges-analytics.md)
192
193
## Common Types
194
195
```python { .api }
196
class Configuration:
197
def __init__(sandbox: bool = False) -> None
198
access_token: str
199
api_key: dict
200
debug: bool
201
202
class ApiClient:
203
def __init__(configuration: Configuration = None) -> None
204
def call_api(resource_path: str, method: str, **kwargs) -> object
205
def set_default_header(header_name: str, header_value: str) -> None
206
207
# Request Models
208
class PlaceOrderRequest:
209
quantity: int
210
product: str # 'I' (Intraday), 'D' (Delivery), 'M' (Margin)
211
validity: str # 'DAY', 'IOC'
212
price: float
213
tag: str
214
instrument_token: str # Format: "EXCHANGE_SEGMENT|TOKEN"
215
order_type: str # 'MARKET', 'LIMIT', 'SL', 'SL-M'
216
transaction_type: str # 'BUY', 'SELL'
217
disclosed_quantity: int
218
trigger_price: float
219
is_amo: bool # After Market Order
220
221
class ModifyOrderRequest:
222
quantity: int
223
validity: str
224
price: float
225
order_id: str
226
order_type: str
227
disclosed_quantity: int
228
trigger_price: float
229
230
class ConvertPositionRequest:
231
instrument_token: str
232
new_product: str
233
old_product: str
234
transaction_type: str
235
quantity: int
236
237
# Response Models
238
class GetProfileResponse:
239
status: str
240
data: ProfileData
241
242
class GetOrderBookResponse:
243
status: str
244
data: list[OrderBookData]
245
246
class GetPositionResponse:
247
status: str
248
data: list[PositionData]
249
250
class GetHoldingsResponse:
251
status: str
252
data: list[HoldingsData]
253
254
# Data Models
255
class ProfileData:
256
user_id: str
257
user_name: str
258
user_type: str
259
poa: bool
260
is_active: bool
261
broker: str
262
exchanges: list[str]
263
products: list[str]
264
265
class OrderBookData:
266
order_id: str
267
exchange: str
268
instrument_token: str
269
product: str
270
order_type: str
271
transaction_type: str
272
quantity: int
273
price: float
274
status: str
275
276
class PositionData:
277
exchange: str
278
instrument_token: str
279
product: str
280
quantity: int
281
buy_price: float
282
sell_price: float
283
pnl: float
284
285
class HoldingsData:
286
instrument_token: str
287
exchange: str
288
tradingsymbol: str
289
quantity: int
290
t1_quantity: int
291
average_price: float
292
last_price: float
293
pnl: float
294
```