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.
The SDK supports passing an algorithm name for order tracking and management. When provided, the SDK will pass the algo name as X-Algo-Name header.
import upstox_client
from upstox_client.rest import ApiException
configuration = upstox_client.Configuration()
configuration.access_token = 'ACCESS_TOKEN'
api_instance = upstox_client.OrderApiV3(upstox_client.ApiClient(configuration))
body = upstox_client.PlaceOrderV3Request(quantity=1, product="D", validity="DAY", price=20,
instrument_token="NSE_EQ|INE528G01035", order_type="LIMIT",
transaction_type="BUY", disclosed_quantity=0, trigger_price=0,
is_amo=False, slice=True)
try:
api_response = api_instance.place_order(body, algo_name="your-algo-name")
print(api_response)
except ApiException as e:
print("Exception when calling OrderApiV3->place_order: %s\n" % e)
Other order methods (modify, cancel, etc.) follow the same pattern by accepting an optional algo_name as a keyword parameter.
The examples/ folder contains ready-to-run scripts covering common API use cases:
| Folder | Description |
|---|---|
examples/login/ |
OAuth2 authorization flow and access token generation |
examples/orders/ |
Place, modify, cancel, and retrieve orders |
examples/market_quote/ |
Fetch live quotes, OHLC, and market depth |
examples/portfolio/ |
View holdings, positions, and P&L |
examples/strategies/ |
33 options trading strategies across four categories |
The interactive_examples/ directory contains 47 ready-to-run CLI scripts across 8 categories: instrument search, futures basis, options strategies, options analytics, arbitrage, historical analysis, portfolio screening, and market data. See the interactive_examples README for details.
The examples/strategies/ folder is organized by market outlook:
| Category | Strategies |
|---|---|
| Bullish | Buy Call, Sell Put, Bull Call Spread, Bull Put Spread, Bull Butterfly, Bull Condor, Long Calendar with Calls, Long Synthetic Future, Call Ratio Back Spread, Range Forward |
| Bearish | Buy Put, Sell Call, Bear Call Spread, Bear Put Spread, Bear Butterfly, Bear Condor, Long Calendar with Puts, Short Synthetic Future, Put Ratio Back Spread, Risk Reversal |
| Neutral | Short Straddle, Short Strangle, Iron Butterfly, Batman, Short Iron Condor |
| Others | Long Straddle, Long Strangle, Call Ratio Spread, Put Ratio Spread, Long Iron Butterfly, Long Iron Condor, Strip, Strap |
Each strategy script automatically selects the correct Nifty 50 strikes using InstrumentsApi.search_instrument() and places orders via OrderApiV3. Just set your ACCESS_TOKEN and run.
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:
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.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.
full, ltpc, option_greeks or full_d30).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.
import upstox_client
def main():
configuration = upstox_client.Configuration()
access_token = <ACCESS_TOKEN>
configuration.access_token = access_token
streamer = upstox_client.MarketDataStreamerV3(
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()
import upstox_client
import time
def main():
configuration = upstox_client.Configuration()
access_token = <ACCESS_TOKEN>
configuration.access_token = access_token
streamer = upstox_client.MarketDataStreamerV3(
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()
import upstox_client
import time
def main():
configuration = upstox_client.Configuration()
access_token = <ACCESS_TOKEN>
configuration.access_token = access_token
streamer = upstox_client.MarketDataStreamerV3(
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()
import upstox_client
import time
def main():
configuration = upstox_client.Configuration()
access_token = <ACCESS_TOKEN>
configuration.access_token = access_token
streamer = upstox_client.MarketDataStreamerV3(
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()
import upstox_client
import time
def main():
configuration = upstox_client.Configuration()
access_token = <ACCESS_TOKEN>
configuration.access_token = access_token
streamer = upstox_client.MarketDataStreamerV3(
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()
import upstox_client
def main():
configuration = upstox_client.Configuration()
access_token = <ACCESS_TOKEN>
configuration.access_token = access_token
streamer = upstox_client.MarketDataStreamerV3(
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()
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, holding, and GTT order 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,
gtt_update=True)
streamer.on("message", on_message)
streamer.on("open", on_open)
streamer.connect()
if __name__ == "__main__":
main()
True to receive real-time order updates (default: True)True to receive position updates (default: False)True to receive holding updates (default: False)True to receive GTT order updates (default: False)