The official Python client for communicating with the Upstox API.
Upstox API is a set of rest APIs that provide data required to build a complete investment and trading platform. Execute orders in real time, manage user portfolio, stream live market data (using Websocket), and more, with the easy to understand API collection.
This Python package is automatically generated by the Swagger Codegen project.
Python 2.7 and 3.4+
If the python package is hosted on Github, you can install directly from Github
pip install upstox-python-sdk
(you may need to run pip
with root permission: sudo pip install upstox-python-sdk
)
Then import the package:
import upstox_client
Install via Setuptools.
python setup.py install --user
(or sudo python setup.py install
to install the package for all users)
Then import the package:
import upstox_client
We recommend using the sandbox environment for testing purposes. To enable sandbox mode, set the sandbox
flag to True
in the configuration object.
import upstox_client
from upstox_client.rest import ApiException
configuration = upstox_client.Configuration(sandbox=True)
configuration.access_token = 'SANDBOX_ACCESS_TOKEN'
api_instance = upstox_client.OrderApiV3(upstox_client.ApiClient(configuration))
body = upstox_client.PlaceOrderV3Request(quantity=1, product="D",validity="DAY", price=9.12, tag="string", instrument_token="NSE_EQ|INE669E01016", order_type="LIMIT",
transaction_type="BUY", disclosed_quantity=0, trigger_price=0.0, is_amo=True, slice=True)
try:
api_response = api_instance.place_order(body)
print(api_response)
except ApiException as e:
print("Exception when calling OrderApi->place_order: %s\n" % e)
To learn more about the sandbox environment and the available sandbox APIs, please visit the Upstox API documentation - Sandbox.
Sample Implementations can be found within /examples
folder.
All URIs are relative to https://api.upstox.com/v2/
Class | Method | HTTP request | Description |
---|---|---|---|
ChargeApi | get_brokerage | GET /v2/charges/brokerage | Brokerage details |
ChargeApi | post_margin | POST /v2/charges/margin | Calculate Margin |
HistoryApi | get_historical_candle_data | GET /v2/historical-candle/{instrumentKey}/{interval}/{to_date} | Historical candle data |
HistoryApi | get_historical_candle_data1 | GET /v2/historical-candle/{instrumentKey}/{interval}/{to_date}/{from_date} | Historical candle data |
HistoryApi | get_intra_day_candle_data | GET /v2/historical-candle/intraday/{instrumentKey}/{interval} | Intra day candle data |
LoginApi | authorize | GET /v2/login/authorization/dialog | Authorize API |
LoginApi | init_token_request_for_indie_user | POST /v3/login/auth/token/request/{client_id} | Init token API |
LoginApi | logout | DELETE /v2/logout | Logout |
LoginApi | token | POST /v2/login/authorization/token | Get token API |
MarketHolidaysAndTimingsApi | get_exchange_timings | GET /v2/market/timings/{date} | Get Exchange Timings on particular date |
MarketHolidaysAndTimingsApi | get_holiday | GET /v2/market/holidays/{date} | Get Holiday on particular date |
MarketHolidaysAndTimingsApi | get_holidays | GET /v2/market/holidays | Get Holiday list of current year |
MarketHolidaysAndTimingsApi | get_market_status | GET /v2/market/status/{exchange} | Get Market status for particular exchange |
MarketQuoteApi | get_full_market_quote | GET /v2/market-quote/quotes | Market quotes and instruments - Full market quotes |
MarketQuoteApi | get_market_quote_ohlc | GET /v2/market-quote/ohlc | Market quotes and instruments - OHLC quotes |
MarketQuoteApi | ltp | GET /v2/market-quote/ltp | Market quotes and instruments - LTP quotes. |
OptionsApi | get_option_contracts | GET /v2/option/contract | Get option contracts |
OptionsApi | get_put_call_option_chain | GET /v2/option/chain | Get option chain |
OrderApi | cancel_multi_order | DELETE /v2/order/multi/cancel | Cancel multi order |
OrderApi | cancel_order | DELETE /v2/order/cancel | Cancel order |
OrderApi | exit_positions | POST /v2/order/positions/exit | Exit all positions |
OrderApi | get_order_book | GET /v2/order/retrieve-all | Get order book |
OrderApi | get_order_details | GET /v2/order/history | Get order history |
OrderApi | get_order_status | GET /v2/order/details | Get order details |
OrderApi | get_trade_history | GET /v2/order/trades/get-trades-for-day | Get trades |
OrderApi | get_trades_by_order | GET /v2/order/trades | Get trades for order |
OrderApi | modify_order | PUT /v2/order/modify | Modify order |
OrderApi | place_multi_order | POST /v2/order/multi/place | Place multi order |
OrderApi | place_order | POST /v2/order/place | Place order |
PortfolioApi | convert_positions | PUT /v2/portfolio/convert-position | Convert Positions |
PortfolioApi | get_holdings | GET /v2/portfolio/long-term-holdings | Get Holdings |
PortfolioApi | get_positions | GET /v2/portfolio/short-term-positions | Get Positions |
PostTradeApi | get_trades_by_date_range | GET /v2/charges/historical-trades | Get historical trades |
TradeProfitAndLossApi | get_profit_and_loss_charges | GET /v2/trade/profit-loss/charges | Get profit and loss on trades |
TradeProfitAndLossApi | get_trade_wise_profit_and_loss_data | GET /v2/trade/profit-loss/data | Get Trade-wise Profit and Loss Report Data |
TradeProfitAndLossApi | get_trade_wise_profit_and_loss_meta_data | GET /v2/trade/profit-loss/metadata | Get profit and loss meta data on trades |
UserApi | get_profile | GET /v2/user/profile | Get profile |
UserApi | get_user_fund_margin | GET /v2/user/get-funds-and-margin | Get User Fund And Margin |
WebsocketApi | get_market_data_feed | GET /v2/feed/market-data-feed | Market Data Feed |
WebsocketApi | get_market_data_feed_authorize | GET /v2/feed/market-data-feed/authorize | Market Data Feed Authorize |
WebsocketApi | get_portfolio_stream_feed | GET /v2/feed/portfolio-stream-feed | Portfolio Stream Feed |
WebsocketApi | get_portfolio_stream_feed_authorize | GET /v2/feed/portfolio-stream-feed/authorize | Portfolio Stream Feed Authorize |
OrderApiV3 | cancel_order | DELETE /v3/order/cancel | |
OrderApiV3 | modify_order | PUT /v3/order/modify | |
OrderApiV3 | place_order | POST /v3/order/place |
Connecting to the WebSocket for market and portfolio updates is streamlined through two primary Feeder functions:
Both functions are designed to simplify the process of subscribing to essential data streams, ensuring users have quick and easy access to the information they need.
The `MarketDataStreamerV3` interface is designed for effortless connection to the market WebSocket, enabling users to receive instantaneous updates on various instruments. The following example demonstrates how to quickly set up and start receiving market updates for selected instrument keys:
```python
import upstox_client
def on_message(message):
print(message)
def main():
configuration = upstox_client.Configuration()
access_token =
The `MarketDataStreamer` interface is designed for effortless connection to the market WebSocket, enabling users to receive instantaneous updates on various instruments. The following example demonstrates how to quickly set up and start receiving market updates for selected instrument keys:
```python
import upstox_client
def on_message(message):
print(message)
def main():
configuration = upstox_client.Configuration()
access_token =
1. Subscribing to Market Data on Connection Open with MarketDataStreamerV3
```python
import upstox_client
def main():
configuration = upstox_client.Configuration()
access_token =
2. Subscribing to Instruments with Delays
```python
import upstox_client
import time
def main():
configuration = upstox_client.Configuration()
access_token =
3. Subscribing and Unsubscribing to Instruments
```python
import upstox_client
import time
def main():
configuration = upstox_client.Configuration()
access_token =
4. Subscribe, Change Mode and Unsubscribe
```python
import upstox_client
import time
def main():
configuration = upstox_client.Configuration()
access_token =
5. Disable Auto-Reconnect
```python
import upstox_client
import time
def main():
configuration = upstox_client.Configuration()
access_token =
6. Modify Auto-Reconnect parameters
```python
import upstox_client
def main():
configuration = upstox_client.Configuration()
access_token =
</p>
</details>
V2
1. Subscribing to Market Data on Connection Open with MarketDataStreamer
```python
import upstox_client
def main():
configuration = upstox_client.Configuration()
access_token =
2. Subscribing to Instruments with Delays
```python
import upstox_client
import time
def main():
configuration = upstox_client.Configuration()
access_token =
3. Subscribing and Unsubscribing to Instruments
```python
import upstox_client
import time
def main():
configuration = upstox_client.Configuration()
access_token =
4. Subscribe, Change Mode and Unsubscribe
```python
import upstox_client
import time
def main():
configuration = upstox_client.Configuration()
access_token =
5. Disable Auto-Reconnect
```python
import upstox_client
import time
def main():
configuration = upstox_client.Configuration()
access_token =
6. Modify Auto-Reconnect parameters
```python
import upstox_client
def main():
configuration = upstox_client.Configuration()
access_token =
</p>
</details>
### PortfolioDataStreamer
Connecting to the Portfolio WebSocket for real-time order updates is straightforward with the PortfolioDataStreamer function. Below is a concise guide to get you started on receiving updates:
```python
import upstox_client
def on_message(message):
print(message)
def main():
configuration = upstox_client.Configuration()
access_token =
Position, holding, and GTT order updates can be enabled by setting the corresponding flag to `True` in the constructor of the `PortfolioDataStreamer` class.
```python
import upstox_client
import data_token
def on_message(message):
print(message)
def on_open():
print("connection opened")
def main():
configuration = upstox_client.Configuration()
configuration.access_token =
### Exploring the PortfolioDataStreamer Functionality
#### Constructor Parameters
1. **api_client**: Your API client instance
2. **order_update**: Set to `True` to receive real-time order updates (default: `True`)
3. **position_update**: Set to `True` to receive position updates (default: `False`)
4. **holding_update**: Set to `True` to receive holding updates (default: `False`)
5. **gtt_update**: Set to `True` to receive GTT order updates (default: `False`)
#### Functions
1. **constructor PortfolioDataStreamer()**: Initializes the streamer.
2. **connect()**: Establishes the WebSocket connection.
6. **disconnect()**: Ends the active WebSocket connection.
7. **auto_reconnect(enable, interval, retryCount)**: Customizes auto-reconnect functionality. Parameters include a flag to enable/disable it, the interval(in seconds) between attempts, and the maximum number of retries.
#### Events
- **open**: Emitted upon successful connection establishment.
- **close**: Indicates the WebSocket connection has been closed.
- **message**: Delivers market updates.
- **error**: Signals an error has occurred.
- **reconnecting**: Announced when a reconnect attempt is initiated.
- **autoReconnectStopped**: Informs when auto-reconnect efforts have ceased after exhausting the retry count.
## Documentation For Models
- [AnalyticsData](/upstox-python/docs/AnalyticsData.html)
- [ApiGatewayErrorResponse](/upstox-python/docs/ApiGatewayErrorResponse.html)
- [BatchExecutionSummary](/upstox-python/docs/BatchExecutionSummary.html)
- [BrokerageData](/upstox-python/docs/BrokerageData.html)
- [BrokerageTaxes](/upstox-python/docs/BrokerageTaxes.html)
- [BrokerageWrapperData](/upstox-python/docs/BrokerageWrapperData.html)
- [CancelOrExitMultiOrderData](/upstox-python/docs/CancelOrExitMultiOrderData.html)
- [CancelOrExitMultiOrderResponse](/upstox-python/docs/CancelOrExitMultiOrderResponse.html)
- [CancelOrExitOrderErrorData](/upstox-python/docs/CancelOrExitOrderErrorData.html)
- [CancelOrderData](/upstox-python/docs/CancelOrderData.html)
- [CancelOrderResponse](/upstox-python/docs/CancelOrderResponse.html)
- [CancelOrderV3Response](/upstox-python/docs/CancelOrderV3Response.html)
- [ConvertPositionData](/upstox-python/docs/ConvertPositionData.html)
- [ConvertPositionRequest](/upstox-python/docs/ConvertPositionRequest.html)
- [ConvertPositionResponse](/upstox-python/docs/ConvertPositionResponse.html)
- [Depth](/upstox-python/docs/Depth.html)
- [DepthMap](/upstox-python/docs/DepthMap.html)
- [DpPlan](/upstox-python/docs/DpPlan.html)
- [ExchangeTimingData](/upstox-python/docs/ExchangeTimingData.html)
- [GetBrokerageResponse](/upstox-python/docs/GetBrokerageResponse.html)
- [GetExchangeTimingResponse](/upstox-python/docs/GetExchangeTimingResponse.html)
- [GetFullMarketQuoteResponse](/upstox-python/docs/GetFullMarketQuoteResponse.html)
- [GetHistoricalCandleResponse](/upstox-python/docs/GetHistoricalCandleResponse.html)
- [GetHoldingsResponse](/upstox-python/docs/GetHoldingsResponse.html)
- [GetHolidayResponse](/upstox-python/docs/GetHolidayResponse.html)
- [GetIntraDayCandleResponse](/upstox-python/docs/GetIntraDayCandleResponse.html)
- [GetMarketQuoteLastTradedPriceResponse](/upstox-python/docs/GetMarketQuoteLastTradedPriceResponse.html)
- [GetMarketQuoteOHLCResponse](/upstox-python/docs/GetMarketQuoteOHLCResponse.html)
- [GetMarketStatusResponse](/upstox-python/docs/GetMarketStatusResponse.html)
- [GetOptionChainResponse](/upstox-python/docs/GetOptionChainResponse.html)
- [GetOptionContractResponse](/upstox-python/docs/GetOptionContractResponse.html)
- [GetOrderBookResponse](/upstox-python/docs/GetOrderBookResponse.html)
- [GetOrderDetailsResponse](/upstox-python/docs/GetOrderDetailsResponse.html)
- [GetOrderResponse](/upstox-python/docs/GetOrderResponse.html)
- [GetPositionResponse](/upstox-python/docs/GetPositionResponse.html)
- [GetProfileResponse](/upstox-python/docs/GetProfileResponse.html)
- [GetProfitAndLossChargesResponse](/upstox-python/docs/GetProfitAndLossChargesResponse.html)
- [GetTradeResponse](/upstox-python/docs/GetTradeResponse.html)
- [GetTradeWiseProfitAndLossDataResponse](/upstox-python/docs/GetTradeWiseProfitAndLossDataResponse.html)
- [GetTradeWiseProfitAndLossMetaDataResponse](/upstox-python/docs/GetTradeWiseProfitAndLossMetaDataResponse.html)
- [GetUserFundMarginResponse](/upstox-python/docs/GetUserFundMarginResponse.html)
- [HistoricalCandleData](/upstox-python/docs/HistoricalCandleData.html)
- [HoldingsData](/upstox-python/docs/HoldingsData.html)
- [HolidayData](/upstox-python/docs/HolidayData.html)
- [IndieUserInitTokenData](/upstox-python/docs/IndieUserInitTokenData.html)
- [IndieUserInitTokenResponse](/upstox-python/docs/IndieUserInitTokenResponse.html)
- [IndieUserTokenRequest](/upstox-python/docs/IndieUserTokenRequest.html)
- [Instrument](/upstox-python/docs/Instrument.html)
- [InstrumentData](/upstox-python/docs/InstrumentData.html)
- [IntraDayCandleData](/upstox-python/docs/IntraDayCandleData.html)
- [LogoutResponse](/upstox-python/docs/LogoutResponse.html)
- [Margin](/upstox-python/docs/Margin.html)
- [MarginData](/upstox-python/docs/MarginData.html)
- [MarginRequest](/upstox-python/docs/MarginRequest.html)
- [MarketData](/upstox-python/docs/MarketData.html)
- [MarketQuoteOHLC](/upstox-python/docs/MarketQuoteOHLC.html)
- [MarketQuoteSymbol](/upstox-python/docs/MarketQuoteSymbol.html)
- [MarketQuoteSymbolLtp](/upstox-python/docs/MarketQuoteSymbolLtp.html)
- [MarketStatusData](/upstox-python/docs/MarketStatusData.html)
- [ModifyOrderData](/upstox-python/docs/ModifyOrderData.html)
- [ModifyOrderRequest](/upstox-python/docs/ModifyOrderRequest.html)
- [ModifyOrderResponse](/upstox-python/docs/ModifyOrderResponse.html)
- [ModifyOrderV3Response](/upstox-python/docs/ModifyOrderV3Response.html)
- [MultiOrderData](/upstox-python/docs/MultiOrderData.html)
- [MultiOrderError](/upstox-python/docs/MultiOrderError.html)
- [MultiOrderRequest](/upstox-python/docs/MultiOrderRequest.html)
- [MultiOrderResponse](/upstox-python/docs/MultiOrderResponse.html)
- [MultiOrderSummary](/upstox-python/docs/MultiOrderSummary.html)
- [MultiOrderV3Data](/upstox-python/docs/MultiOrderV3Data.html)
- [OAuthClientException](/upstox-python/docs/OAuthClientException.html)
- [OAuthClientExceptionCause](/upstox-python/docs/OAuthClientExceptionCause.html)
- [OAuthClientExceptionCauseStackTrace](/upstox-python/docs/OAuthClientExceptionCauseStackTrace.html)
- [OAuthClientExceptionCauseSuppressed](/upstox-python/docs/OAuthClientExceptionCauseSuppressed.html)
- [Ohlc](/upstox-python/docs/Ohlc.html)
- [OptionStrikeData](/upstox-python/docs/OptionStrikeData.html)
- [OrderBookData](/upstox-python/docs/OrderBookData.html)
- [OrderData](/upstox-python/docs/OrderData.html)
- [OrderMetadata](/upstox-python/docs/OrderMetadata.html)
- [OtherTaxes](/upstox-python/docs/OtherTaxes.html)
- [PlaceOrderData](/upstox-python/docs/PlaceOrderData.html)
- [PlaceOrderRequest](/upstox-python/docs/PlaceOrderRequest.html)
- [PlaceOrderResponse](/upstox-python/docs/PlaceOrderResponse.html)
- [PlaceOrderV3Request](/upstox-python/docs/PlaceOrderV3Request.html)
- [PlaceOrderV3Response](/upstox-python/docs/PlaceOrderV3Response.html)
- [PositionData](/upstox-python/docs/PositionData.html)
- [PostMarginResponse](/upstox-python/docs/PostMarginResponse.html)
- [Problem](/upstox-python/docs/Problem.html)
- [ProfileData](/upstox-python/docs/ProfileData.html)
- [ProfitAndLossChargesData](/upstox-python/docs/ProfitAndLossChargesData.html)
- [ProfitAndLossChargesTaxes](/upstox-python/docs/ProfitAndLossChargesTaxes.html)
- [ProfitAndLossChargesWrapperData](/upstox-python/docs/ProfitAndLossChargesWrapperData.html)
- [ProfitAndLossMetaData](/upstox-python/docs/ProfitAndLossMetaData.html)
- [ProfitAndLossMetaDataWrapper](/upstox-python/docs/ProfitAndLossMetaDataWrapper.html)
- [ProfitAndLossOtherChargesTaxes](/upstox-python/docs/ProfitAndLossOtherChargesTaxes.html)
- [PutCallOptionChainData](/upstox-python/docs/PutCallOptionChainData.html)
- [TokenRequest](/upstox-python/docs/TokenRequest.html)
- [TokenResponse](/upstox-python/docs/TokenResponse.html)
- [TradeData](/upstox-python/docs/TradeData.html)
- [TradeHistoryResponse](/upstox-python/docs/TradeHistoryResponse.html)
- [TradeHistoryResponseMetaData](/upstox-python/docs/TradeHistoryResponseMetaData.html)
- [TradeHistoryResponsePageData](/upstox-python/docs/TradeHistoryResponsePageData.html)
- [TradeHistoryResponseTradeData](/upstox-python/docs/TradeHistoryResponseTradeData.html)
- [TradeWiseMetaData](/upstox-python/docs/TradeWiseMetaData.html)
- [TradeWiseProfitAndLossData](/upstox-python/docs/TradeWiseProfitAndLossData.html)
- [UserFundMarginData](/upstox-python/docs/UserFundMarginData.html)
- [WebsocketAuthRedirectResponse](/upstox-python/docs/WebsocketAuthRedirectResponse.html)
- [WebsocketAuthRedirectResponseData](/upstox-python/docs/WebsocketAuthRedirectResponseData.html)