Skip to content

Repository files navigation

Upstox Python SDK for API v2

PyPI

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.14.0
  • Build package: io.swagger.codegen.v3.generators.python.PythonClientCodegen

This Python package is automatically generated by the Swagger Codegen project.

Documentation.

Upstox API 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:

importupstox_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:

importupstox_client

Sandbox Mode

We recommend using the sandbox environment for testing purposes. To enable sandbox mode, set the sandbox flag to True in the configuration object.

importupstox_clientfromupstox_client.restimportApiExceptionconfiguration=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)
exceptApiExceptionase:
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.

Examples

Sample Implementations can be found within /examples folder.

Documentation for API Endpoints

All URIs are relative to https://api.upstox.com/v2/

ClassMethodHTTP requestDescription
ChargeApiget_brokerageGET /v2/charges/brokerageBrokerage details
ChargeApipost_marginPOST /v2/charges/marginCalculate Margin
HistoryApiget_historical_candle_dataGET /v2/historical-candle/{instrumentKey}/{interval}/{to_date}Historical candle data
HistoryApiget_historical_candle_data1GET /v2/historical-candle/{instrumentKey}/{interval}/{to_date}/{from_date}Historical candle data
HistoryApiget_intra_day_candle_dataGET /v2/historical-candle/intraday/{instrumentKey}/{interval}Intra day candle data
LoginApiauthorizeGET /v2/login/authorization/dialogAuthorize API
LoginApiinit_token_request_for_indie_userPOST /v3/login/auth/token/request/{client_id}Init token API
LoginApilogoutDELETE /v2/logoutLogout
LoginApitokenPOST /v2/login/authorization/tokenGet token API
MarketHolidaysAndTimingsApiget_exchange_timingsGET /v2/market/timings/{date}Get Exchange Timings on particular date
MarketHolidaysAndTimingsApiget_holidayGET /v2/market/holidays/{date}Get Holiday on particular date
MarketHolidaysAndTimingsApiget_holidaysGET /v2/market/holidaysGet Holiday list of current year
MarketHolidaysAndTimingsApiget_market_statusGET /v2/market/status/{exchange}Get Market status for particular exchange
MarketQuoteApiget_full_market_quoteGET /v2/market-quote/quotesMarket quotes and instruments - Full market quotes
MarketQuoteApiget_market_quote_ohlcGET /v2/market-quote/ohlcMarket quotes and instruments - OHLC quotes
MarketQuoteApiltpGET /v2/market-quote/ltpMarket quotes and instruments - LTP quotes.
OptionsApiget_option_contractsGET /v2/option/contractGet option contracts
OptionsApiget_put_call_option_chainGET /v2/option/chainGet option chain
OrderApicancel_multi_orderDELETE /v2/order/multi/cancelCancel multi order
OrderApicancel_orderDELETE /v2/order/cancelCancel order
OrderApiexit_positionsPOST /v2/order/positions/exitExit all positions
OrderApiget_order_bookGET /v2/order/retrieve-allGet order book
OrderApiget_order_detailsGET /v2/order/historyGet order history
OrderApiget_order_statusGET /v2/order/detailsGet order details
OrderApiget_trade_historyGET /v2/order/trades/get-trades-for-dayGet trades
OrderApiget_trades_by_orderGET /v2/order/tradesGet trades for order
OrderApimodify_orderPUT /v2/order/modifyModify order
OrderApiplace_multi_orderPOST /v2/order/multi/placePlace multi order
OrderApiplace_orderPOST /v2/order/placePlace order
PortfolioApiconvert_positionsPUT /v2/portfolio/convert-positionConvert Positions
PortfolioApiget_holdingsGET /v2/portfolio/long-term-holdingsGet Holdings
PortfolioApiget_positionsGET /v2/portfolio/short-term-positionsGet Positions
PostTradeApiget_trades_by_date_rangeGET /v2/charges/historical-tradesGet historical trades
TradeProfitAndLossApiget_profit_and_loss_chargesGET /v2/trade/profit-loss/chargesGet profit and loss on trades
TradeProfitAndLossApiget_trade_wise_profit_and_loss_dataGET /v2/trade/profit-loss/dataGet Trade-wise Profit and Loss Report Data
TradeProfitAndLossApiget_trade_wise_profit_and_loss_meta_dataGET /v2/trade/profit-loss/metadataGet profit and loss meta data on trades
UserApiget_profileGET /v2/user/profileGet profile
UserApiget_user_fund_marginGET /v2/user/get-funds-and-marginGet User Fund And Margin
WebsocketApiget_market_data_feedGET /v2/feed/market-data-feedMarket Data Feed
WebsocketApiget_market_data_feed_authorizeGET /v2/feed/market-data-feed/authorizeMarket Data Feed Authorize
WebsocketApiget_portfolio_stream_feedGET /v2/feed/portfolio-stream-feedPortfolio Stream Feed
WebsocketApiget_portfolio_stream_feed_authorizeGET /v2/feed/portfolio-stream-feed/authorizePortfolio Stream Feed Authorize
OrderApiV3cancel_orderDELETE /v3/order/cancel
OrderApiV3modify_orderPUT /v3/order/modify
OrderApiV3place_orderPOST /v3/order/place

Documentation for Feeder Functions

Connecting to the WebSocket for market and portfolio updates is streamlined through two primary Feeder functions:

  1. MarketDataStreamer: Offers real-time market updates, providing a seamless way to receive instantaneous information on various market instruments.
  2. 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

V3

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:

importupstox_clientdefon_message(message):
print(message)
defmain():
configuration=upstox_client.Configuration()
access_token=<ACCESS_TOKEN>configuration.access_token=access_tokenstreamer=upstox_client.MarketDataStreamerV3(
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 MarketDataStreamerV3 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 MarketDataStreamerV3 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.
  • option_greeks: Contains only option greeks.

Functions

  1. constructor MarketDataStreamerV3(apiClient, instrumentKeys, mode): Initializes the streamer with optional instrument keys and mode (full, ltpc or option_greeks).
  2. connect(): Establishes the WebSocket connection.
  3. subscribe(instrumentKeys, mode): Subscribes to updates for given instrument keys in the specified mode. Both parameters are mandatory.
  4. unsubscribe(instrumentKeys): Stops updates for the specified instrument keys.
  5. changeMode(instrumentKeys, mode): Switches the mode for already subscribed instrument keys.
  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.

The following documentation includes examples to illustrate the usage of these functions and events, providing a practical understanding of how to interact with the MarketDataStreamerV3 effectively.


  1. Subscribing to Market Data on Connection Open with MarketDataStreamerV3
importupstox_clientdefmain():
configuration=upstox_client.Configuration()
access_token=<ACCESS_TOKEN>configuration.access_token=access_tokenstreamer=upstox_client.MarketDataStreamerV3(
upstox_client.ApiClient(configuration))
defon_open():
streamer.subscribe(
["NSE_EQ|INE020B01018", "NSE_EQ|INE467B01029"], "full")
defon_message(message):
print(message)
streamer.on("open", on_open)
streamer.on("message", on_message)
streamer.connect()
if__name__=="__main__":
main()

  1. Subscribing to Instruments with Delays
importupstox_clientimporttimedefmain():
configuration=upstox_client.Configuration()
access_token=<ACCESS_TOKEN>configuration.access_token=access_tokenstreamer=upstox_client.MarketDataStreamerV3(
upstox_client.ApiClient(configuration))
defon_open():
streamer.subscribe(
["NSE_EQ|INE020B01018"], "full")
# Handle incoming market data messages\defon_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()

  1. Subscribing and Unsubscribing to Instruments
importupstox_clientimporttimedefmain():
configuration=upstox_client.Configuration()
access_token=<ACCESS_TOKEN>configuration.access_token=access_tokenstreamer=upstox_client.MarketDataStreamerV3(
upstox_client.ApiClient(configuration))
defon_open():
print("Connected. Subscribing to instrument keys.")
streamer.subscribe(
["NSE_EQ|INE020B01018", "NSE_EQ|INE467B01029"], "full")
# Handle incoming market data messages\defon_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()

  1. Subscribe, Change Mode and Unsubscribe
importupstox_clientimporttimedefmain():
configuration=upstox_client.Configuration()
access_token=<ACCESS_TOKEN>configuration.access_token=access_tokenstreamer=upstox_client.MarketDataStreamerV3(
upstox_client.ApiClient(configuration))
defon_open():
print("Connected. Subscribing to instrument keys.")
streamer.subscribe(
["NSE_EQ|INE020B01018", "NSE_EQ|INE467B01029"], "full")
# Handle incoming market data messages\defon_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()

  1. Disable Auto-Reconnect
importupstox_clientimporttimedefmain():
configuration=upstox_client.Configuration()
access_token=<ACCESS_TOKEN>configuration.access_token=access_tokenstreamer=upstox_client.MarketDataStreamerV3(
upstox_client.ApiClient(configuration))
defon_reconnection_halt(message):
print(message)
streamer.on("autoReconnectStopped", on_reconnection_halt)
# Disable auto-reconnect featurestreamer.auto_reconnect(False)
streamer.connect()
if__name__=="__main__":
main()

  1. Modify Auto-Reconnect parameters
importupstox_clientdefmain():
configuration=upstox_client.Configuration()
access_token=<ACCESS_TOKEN>configuration.access_token=access_tokenstreamer=upstox_client.MarketDataStreamerV3(
upstox_client.ApiClient(configuration))
# Modify auto-reconnect parameters: enable it, set interval to 10 seconds, and retry count to 3streamer.auto_reconnect(True, 10, 3)
streamer.connect()
if__name__=="__main__":
main()

V2

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:

importupstox_clientdefon_message(message):
print(message)
defmain():
configuration=upstox_client.Configuration()
access_token=<ACCESS_TOKEN>configuration.access_token=access_tokenstreamer=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

  1. constructor MarketDataStreamer(apiClient, instrumentKeys, mode): Initializes the streamer with optional instrument keys and mode (full or ltpc).
  2. connect(): Establishes the WebSocket connection.
  3. subscribe(instrumentKeys, mode): Subscribes to updates for given instrument keys in the specified mode. Both parameters are mandatory.
  4. unsubscribe(instrumentKeys): Stops updates for the specified instrument keys.
  5. changeMode(instrumentKeys, mode): Switches the mode for already subscribed instrument keys.
  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.

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.


  1. Subscribing to Market Data on Connection Open with MarketDataStreamer
importupstox_clientdefmain():
configuration=upstox_client.Configuration()
access_token=<ACCESS_TOKEN>configuration.access_token=access_tokenstreamer=upstox_client.MarketDataStreamer(
upstox_client.ApiClient(configuration))
defon_open():
streamer.subscribe(
["NSE_EQ|INE020B01018", "NSE_EQ|INE467B01029"], "full")
defon_message(message):
print(message)
streamer.on("open", on_open)
streamer.on("message", on_message)
streamer.connect()
if__name__=="__main__":
main()

  1. Subscribing to Instruments with Delays
importupstox_clientimporttimedefmain():
configuration=upstox_client.Configuration()
access_token=<ACCESS_TOKEN>configuration.access_token=access_tokenstreamer=upstox_client.MarketDataStreamer(
upstox_client.ApiClient(configuration))
defon_open():
streamer.subscribe(
["NSE_EQ|INE020B01018"], "full")
# Handle incoming market data messages\defon_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()

  1. Subscribing and Unsubscribing to Instruments
importupstox_clientimporttimedefmain():
configuration=upstox_client.Configuration()
access_token=<ACCESS_TOKEN>configuration.access_token=access_tokenstreamer=upstox_client.MarketDataStreamer(
upstox_client.ApiClient(configuration))
defon_open():
print("Connected. Subscribing to instrument keys.")
streamer.subscribe(
["NSE_EQ|INE020B01018", "NSE_EQ|INE467B01029"], "full")
# Handle incoming market data messages\defon_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()

  1. Subscribe, Change Mode and Unsubscribe
importupstox_clientimporttimedefmain():
configuration=upstox_client.Configuration()
access_token=<ACCESS_TOKEN>configuration.access_token=access_tokenstreamer=upstox_client.MarketDataStreamer(
upstox_client.ApiClient(configuration))
defon_open():
print("Connected. Subscribing to instrument keys.")
streamer.subscribe(
["NSE_EQ|INE020B01018", "NSE_EQ|INE467B01029"], "full")
# Handle incoming market data messages\defon_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()

  1. Disable Auto-Reconnect
importupstox_clientimporttimedefmain():
configuration=upstox_client.Configuration()
access_token=<ACCESS_TOKEN>configuration.access_token=access_tokenstreamer=upstox_client.MarketDataStreamer(
upstox_client.ApiClient(configuration))
defon_reconnection_halt(message):
print(message)
streamer.on("autoReconnectStopped", on_reconnection_halt)
# Disable auto-reconnect featurestreamer.auto_reconnect(False)
streamer.connect()
if__name__=="__main__":
main()

  1. Modify Auto-Reconnect parameters
importupstox_clientdefmain():
configuration=upstox_client.Configuration()
access_token=<ACCESS_TOKEN>configuration.access_token=access_tokenstreamer=upstox_client.MarketDataStreamer(
upstox_client.ApiClient(configuration))
# Modify auto-reconnect parameters: enable it, set interval to 10 seconds, and retry count to 3streamer.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:

importupstox_clientdefon_message(message):
print(message)
defmain():
configuration=upstox_client.Configuration()
access_token=<ACCESS_TOKEN>configuration.access_token=access_tokenstreamer=upstox_client.PortfolioDataStreamer(
upstox_client.ApiClient(configuration))
streamer.on("message", on_message)
streamer.connect()
if__name__=="__main__":
main()

Position, holding, and GTT order updates can be enabled by setting the corresponding flag to True in the constructor of the PortfolioDataStreamer class.

importupstox_clientimportdata_tokendefon_message(message):
print(message)
defon_open():
print("connection opened")
defmain():
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,
gtt_update=True)
streamer.on("message", on_message)
streamer.on("open", on_open)
streamer.connect()
if__name__=="__main__":
main()

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.
  3. disconnect(): Ends the active WebSocket connection.
  4. 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

About

Fork of the official Python SDK for accessing Upstox API

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages