Upstox Developer API
Project description
Upstox Python SDK for API v2
Introduction
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.
- API version: v2
- Package version: 2.5.0
- Build package: io.swagger.codegen.v3.generators.python.PythonClientCodegen
This Python package is automatically generated by the Swagger Codegen project.
Documentation.
Requirements.
Python 2.7 and 3.4+
Installation & Usage
pip install
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
Setuptools
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
Examples
Sample Implementations can be found within /examples
folder.
Documentation for API Endpoints
All URIs are relative to https://api.upstox.com/v2/
Class | Method | HTTP request | Description |
---|---|---|---|
ChargeApi | get_brokerage | GET /v2/charges/brokerage | Brokerage details |
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 | 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_order | DELETE /v2/order/cancel | Cancel order |
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_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_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 |
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 |
Documentation for Feeder Functions
Connecting to the WebSocket for market and portfolio updates is streamlined through two primary Feeder functions:
- MarketDataStreamer: Offers real-time market updates, providing a seamless way to receive instantaneous information on various market instruments.
- PortfolioDataStreamer: Delivers updates related to the user's orders, enhancing the ability to track order status and portfolio changes effectively.
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.
Detailed Explanation of Feeder Interface
MarketDataStreamer
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:
import upstox_client
def on_message(message):
print(message)
def main():
configuration = upstox_client.Configuration()
access_token = <ACCESS_TOKEN>
configuration.access_token = access_token
streamer = upstox_client.MarketDataStreamer(
upstox_client.ApiClient(configuration), ["NSE_INDEX|Nifty 50", "NSE_INDEX|Nifty Bank"], "full")
streamer.on("message", on_message)
streamer.connect()
if __name__ == "__main__":
main()
In this example, you first authenticate using an access token, then instantiate MarketDataStreamer with specific instrument keys and a subscription mode. Upon connecting, the streamer listens for market updates, which are logged to the console as they arrive.
Feel free to adjust the access token placeholder and any other specifics to better fit your actual implementation or usage scenario.
Exploring the MarketDataStreamer Functionality
Modes
- ltpc: ltpc provides information solely about the most recent trade, encompassing details such as the last trade price, time of the last trade, quantity traded, and the closing price from the previous day.
- full: The full option offers comprehensive information, including the latest trade prices, D5 depth, 1-minute, 30-minute, and daily candlestick data, along with some additional details.
Functions
- constructor MarketDataStreamer(apiClient, instrumentKeys, mode): Initializes the streamer with optional instrument keys and mode (
full
orltpc
). - connect(): Establishes the WebSocket connection.
- subscribe(instrumentKeys, mode): Subscribes to updates for given instrument keys in the specified mode. Both parameters are mandatory.
- unsubscribe(instrumentKeys): Stops updates for the specified instrument keys.
- changeMode(instrumentKeys, mode): Switches the mode for already subscribed instrument keys.
- disconnect(): Ends the active WebSocket connection.
- 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.
The following documentation includes examples to illustrate the usage of these functions and events, providing a practical understanding of how to interact with the MarketDataStreamer effectively.
- Subscribing to Market Data on Connection Open with MarketDataStreamer
import upstox_client
def main():
configuration = upstox_client.Configuration()
access_token = <ACCESS_TOKEN>
configuration.access_token = access_token
streamer = upstox_client.MarketDataStreamer(
upstox_client.ApiClient(configuration))
def on_open():
streamer.subscribe(
["NSE_EQ|INE020B01018", "NSE_EQ|INE467B01029"], "full")
def on_message(message):
print(message)
streamer.on("open", on_open)
streamer.on("message", on_message)
streamer.connect()
if __name__ == "__main__":
main()
- Subscribing to Instruments with Delays
import upstox_client
import time
def main():
configuration = upstox_client.Configuration()
access_token = <ACCESS_TOKEN>
configuration.access_token = access_token
streamer = upstox_client.MarketDataStreamer(
upstox_client.ApiClient(configuration))
def on_open():
streamer.subscribe(
["NSE_EQ|INE020B01018"], "full")
# Handle incoming market data messages\
def on_message(message):
print(message)
streamer.on("open", on_open)
streamer.on("message", on_message)
streamer.connect()
time.sleep(5)
streamer.subscribe(
["NSE_EQ|INE467B01029"], "full")
if __name__ == "__main__":
main()
- Subscribing and Unsubscribing to Instruments
import upstox_client
import time
def main():
configuration = upstox_client.Configuration()
access_token = <ACCESS_TOKEN>
configuration.access_token = access_token
streamer = upstox_client.MarketDataStreamer(
upstox_client.ApiClient(configuration))
def on_open():
print("Connected. Subscribing to instrument keys.")
streamer.subscribe(
["NSE_EQ|INE020B01018", "NSE_EQ|INE467B01029"], "full")
# Handle incoming market data messages\
def on_message(message):
print(message)
streamer.on("open", on_open)
streamer.on("message", on_message)
streamer.connect()
time.sleep(5)
print("Unsubscribing from instrument keys.")
streamer.unsubscribe(["NSE_EQ|INE020B01018", "NSE_EQ|INE467B01029"])
if __name__ == "__main__":
main()
- Subscribe, Change Mode and Unsubscribe
import upstox_client
import time
def main():
configuration = upstox_client.Configuration()
access_token = <ACCESS_TOKEN>
configuration.access_token = access_token
streamer = upstox_client.MarketDataStreamer(
upstox_client.ApiClient(configuration))
def on_open():
print("Connected. Subscribing to instrument keys.")
streamer.subscribe(
["NSE_EQ|INE020B01018", "NSE_EQ|INE467B01029"], "full")
# Handle incoming market data messages\
def on_message(message):
print(message)
streamer.on("open", on_open)
streamer.on("message", on_message)
streamer.connect()
time.sleep(5)
print("Changing subscription mode to ltpc...")
streamer.change_mode(
["NSE_EQ|INE020B01018", "NSE_EQ|INE467B01029"], "ltpc")
time.sleep(5)
print("Unsubscribing from instrument keys.")
streamer.unsubscribe(["NSE_EQ|INE020B01018", "NSE_EQ|INE467B01029"])
if __name__ == "__main__":
main()
- Disable Auto-Reconnect
import upstox_client
import time
def main():
configuration = upstox_client.Configuration()
access_token = <ACCESS_TOKEN>
configuration.access_token = access_token
streamer = upstox_client.MarketDataStreamer(
upstox_client.ApiClient(configuration))
def on_reconnection_halt(message):
print(message)
streamer.on("autoReconnectStopped", on_reconnection_halt)
# Disable auto-reconnect feature
streamer.auto_reconnect(False)
streamer.connect()
if __name__ == "__main__":
main()
- Modify Auto-Reconnect parameters
import upstox_client
def main():
configuration = upstox_client.Configuration()
access_token = <ACCESS_TOKEN>
configuration.access_token = access_token
streamer = upstox_client.MarketDataStreamer(
upstox_client.ApiClient(configuration))
# Modify auto-reconnect parameters: enable it, set interval to 10 seconds, and retry count to 3
streamer.auto_reconnect(True, 10, 3)
streamer.connect()
if __name__ == "__main__":
main()
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:
import upstox_client
def on_message(message):
print(message)
def main():
configuration = upstox_client.Configuration()
access_token = <ACCESS_TOKEN>
configuration.access_token = access_token
streamer = upstox_client.PortfolioDataStreamer(
upstox_client.ApiClient(configuration))
streamer.on("message", on_message)
streamer.connect()
if __name__ == "__main__":
main()
Position and holding updates can be enabled by setting the corresponding flag to True
in the constructor of the PortfolioDataStreamer
class.
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 = <ACCESS_TOKEN>
streamer = upstox_client.PortfolioDataStreamer(upstox_client.ApiClient(configuration),order_update=True,position_update=True,holding_update=True)
streamer.on("message", on_message)
streamer.on("open", on_open)
streamer.connect()
if __name__ == "__main__":
main()
This example demonstrates initializing the PortfolioDataStreamer, connecting it to the WebSocket, and setting up an event listener to receive and print order updates. Replace <ACCESS_TOKEN> with your valid access token to authenticate the session.
Exploring the PortfolioDataStreamer Functionality
Functions
- constructor PortfolioDataStreamer(): Initializes the streamer.
- connect(): Establishes the WebSocket connection.
- disconnect(): Ends the active WebSocket connection.
- 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
- ApiGatewayErrorResponse
- BrokerageData
- BrokerageTaxes
- BrokerageWrapperData
- CancelOrderData
- CancelOrderResponse
- ConvertPositionData
- ConvertPositionRequest
- ConvertPositionResponse
- Depth
- DepthMap
- DpPlan
- ExchangeTimingData
- GetBrokerageResponse
- GetExchangeTimingResponse
- GetFullMarketQuoteResponse
- GetHistoricalCandleResponse
- GetHoldingsResponse
- GetHolidayResponse
- GetIntraDayCandleResponse
- GetMarketQuoteLastTradedPriceResponse
- GetMarketQuoteOHLCResponse
- GetMarketStatusResponse
- GetOptionChainResponse
- GetOptionContractResponse
- GetOrderBookResponse
- GetOrderResponse
- GetPositionResponse
- GetProfileResponse
- GetProfitAndLossChargesResponse
- GetTradeResponse
- GetTradeWiseProfitAndLossDataResponse
- GetTradeWiseProfitAndLossMetaDataResponse
- GetUserFundMarginResponse
- HistoricalCandleData
- HoldingsData
- HolidayData
- InstrumentData
- IntraDayCandleData
- LogoutResponse
- MarketData
- MarketQuoteOHLC
- MarketQuoteSymbol
- MarketQuoteSymbolLtp
- MarketStatusData
- ModifyOrderData
- ModifyOrderRequest
- ModifyOrderResponse
- OAuthClientException
- OAuthClientExceptionCause
- OAuthClientExceptionCauseStackTrace
- OAuthClientExceptionCauseSuppressed
- Ohlc
- OptionStrikeData
- OrderBookData
- OrderData
- OtherTaxes
- PlaceOrderData
- PlaceOrderRequest
- PlaceOrderResponse
- PositionData
- Problem
- ProfileData
- ProfitAndLossChargesData
- ProfitAndLossChargesTaxes
- ProfitAndLossChargesWrapperData
- ProfitAndLossMetaData
- ProfitAndLossMetaDataWrapper
- ProfitAndLossOtherChargesTaxes
- PutCallOptionChainData
- TokenRequest
- TokenResponse
- TradeData
- TradeWiseMetaData
- TradeWiseProfitAndLossData
- UserFundMarginData
- WebsocketAuthRedirectResponse
- WebsocketAuthRedirectResponseData
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
File details
Details for the file upstox-python-sdk-2.5.0.tar.gz
.
File metadata
- Download URL: upstox-python-sdk-2.5.0.tar.gz
- Upload date:
- Size: 101.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.9.6
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | b59c03550d83216ad0c4068ee4187e6c940f1171c02f85f8f9d044bb5a2c6c32 |
|
MD5 | ae1255ae5a36d124b312dbe4344a6804 |
|
BLAKE2b-256 | 838af79b5d34271c08246a4ea6cea7c3eb5add97c07ee4f20d0beeb9afe595dd |