
Research
/Security News
Toptal’s GitHub Organization Hijacked: 10 Malicious Packages Published
Threat actors hijacked Toptal’s GitHub org, publishing npm packages with malicious payloads that steal tokens and attempt to wipe victim systems.
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 |
ExpiredInstrumentApi | get_expired_future_contracts | GET /v2/expired-instruments/future/contract | Expired instruments - Get future contracts |
ExpiredInstrumentApi | get_expired_historical_candle_data | GET /v2/expired-instruments/historical-candle/{expired_instrument_key}/{interval}/{to_date}/{from_date} | Expired Historical candle data |
ExpiredInstrumentApi | get_expired_option_contracts | GET /v2/expired-instruments/option/contract | Get expired option contracts |
ExpiredInstrumentApi | get_expiries | GET /v2/expired-instruments/expiries | Expired instruments - Get expiries |
HistoryApi | get_historical_candle_data2 | GET /v2/historical-candle/{instrumentKey}/{interval}/{to_date} | Historical candle data |
HistoryApi | get_historical_candle_data3 | GET /v2/historical-candle/{instrumentKey}/{interval}/{to_date}/{from_date} | Historical candle data |
HistoryApi | get_intra_day_candle_data1 | GET /v2/historical-candle/intraday/{instrumentKey}/{interval} | Intra day candle data |
HistoryV3Api | get_historical_candle_data | GET /v3/historical-candle/{instrumentKey}/{unit}/{interval}/{to_date} | Historical candle data |
HistoryV3Api | get_historical_candle_data1 | GET /v3/historical-candle/{instrumentKey}/{unit}/{interval}/{to_date}/{from_date} | Historical candle data |
HistoryV3Api | get_intra_day_candle_data | GET /v3/historical-candle/intraday/{instrumentKey}/{unit}/{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. |
MarketQuoteV3Api | get_ltp | GET /v3/market-quote/ltp | Market quotes and instruments - LTP quotes. |
MarketQuoteV3Api | get_market_quote_ohlc | GET /v3/market-quote/ohlc | Market quotes and instruments - OHLC quotes |
MarketQuoteV3Api | get_market_quote_option_greek | GET /v3/market-quote/option-greek | Market quotes and instruments - Option Greek |
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_mtf_positions | GET /v3/portfolio/mtf-positions | Get MTF positions |
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:
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()
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.
full
or ltpc
).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.
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()
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()
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()
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()
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()
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()
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
)FAQs
Upstox Developer API
We found that upstox-python-sdk demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
/Security News
Threat actors hijacked Toptal’s GitHub org, publishing npm packages with malicious payloads that steal tokens and attempt to wipe victim systems.
Research
/Security News
Socket researchers investigate 4 malicious npm and PyPI packages with 56,000+ downloads that install surveillance malware.
Security News
The ongoing npm phishing campaign escalates as attackers hijack the popular 'is' package, embedding malware in multiple versions.