Skip to content

Commit

Permalink
Merge pull request #85 from upstox/v3-websocket
Browse files Browse the repository at this point in the history
init commit for v3 websocket
  • Loading branch information
KetanGupta12 authored Jan 3, 2025
2 parents 0d68f01 + 856c43c commit 1ab5c44
Show file tree
Hide file tree
Showing 12 changed files with 729 additions and 7 deletions.
287 changes: 284 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ The official Python client for communicating with the <a href="https://upstox.co
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.9.0
- Package version: 2.10.0
- Build package: io.swagger.codegen.v3.generators.python.PythonClientCodegen

This Python package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project.
Expand Down Expand Up @@ -119,6 +119,286 @@ Both functions are designed to simplify the process of subscribing to essential

### MarketDataStreamer

<details>
<summary style="cursor: pointer; font-size: 1.2em;">V3</summary>
<p>

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 = <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.

### 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.

<br/>

1. Subscribing to Market Data on Connection Open with MarketDataStreamerV3

```python
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()
```

<br/>

2. Subscribing to Instruments with Delays

```python
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()

```

<br/>

3. Subscribing and Unsubscribing to Instruments

```python
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()
```

<br/>

4. Subscribe, Change Mode and Unsubscribe

```python
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()
```

<br/>

5. Disable Auto-Reconnect

```python
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()
```

<br/>

6. Modify Auto-Reconnect parameters

```python
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()
```

<br/>
</p>
</details>

<details>
<summary style="cursor: pointer; font-size: 1.2em;">V2</summary>
<p>

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
Expand Down Expand Up @@ -388,6 +668,8 @@ if __name__ == "__main__":
```

<br/>
</p>
</details>

### PortfolioDataStreamer

Expand Down Expand Up @@ -451,8 +733,6 @@ if __name__ == "__main__":

<br/>

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
Expand Down Expand Up @@ -569,3 +849,4 @@ This example demonstrates initializing the PortfolioDataStreamer, connecting it
- [UserFundMarginData](docs/UserFundMarginData.md)
- [WebsocketAuthRedirectResponse](docs/WebsocketAuthRedirectResponse.md)
- [WebsocketAuthRedirectResponseData](docs/WebsocketAuthRedirectResponseData.md)

2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
long_description = (this_directory / "README.md").read_text()

NAME = "upstox-python-sdk"
VERSION = "2.9.0"
VERSION = "2.10.0"
# To install the library, run the following
#
# python setup.py install
Expand Down
22 changes: 21 additions & 1 deletion test/sdk_tests/data_token.py
Original file line number Diff line number Diff line change
@@ -1 +1,21 @@
access_token = ""
access_token = ""


sample_instrument_key = [
"NSE_EQ|INE528G01035", "NSE_EQ|INE399C01030", "BSE_EQ|INE055E01034", "NCD_FO|14245", "NSE_EQ|INE169A01031",
"NSE_EQ|INE437A01024", "NSE_EQ|INE044A01036", "NSE_EQ|INE868B01028", "NSE_EQ|INE202E08219", "NSE_EQ|INE044A01036",
"NSE_EQ|INE257A01026", "NSE_EQ|INE155A01022", "BSE_EQ|INE040A08575", "BSE_EQ|INE040A08567", "NSE_EQ|INE084A01016",
"NSE_EQ|INE121A01024", "NSE_EQ|INE0OGZ15015", "BSE_EQ|INE0OGZ15015", "NSE_EQ|INE364U01010", "NSE_EQ|INE765G01017",
"NSE_EQ|INE239A01024", "BSE_EQ|INE721A07SI5", "NSE_EQ|INE832A01018", "NSE_EQ|INE127D01025", "BCD_FO|2119087",
"BSE_EQ|IN2920210480", "NSE_EQ|INE726G01019", "NSE_FO|114127", "NSE_EQ|INE340Z01019", "NSE_FO|114126",
"NSE_FO|114125", "NSE_FO|114128", "NSE_EQ|IN2120230163", "NSE_FO|38516", "NSE_FO|114133", "NSE_FO|114132",
"BSE_EQ|INE338I14GR3", "BSE_EQ|INE360L01017", "MCX_FO|431658", "MCX_FO|431657", "BSE_EQ|INE896W08020",
"MCX_FO|431656", "BSE_EQ|INE214D01021", "NSE_EQ|IN4920240186", "NSE_EQ|INF789F01GW9", "NSE_EQ|INE0CJF01024",
"NSE_EQ|IN2120230189", "BSE_EQ|INE896W08012", "MCX_FO|431668", "MCX_FO|431667", "MCX_FO|431666",
"BSE_EQ|IN001129C021", "NSE_EQ|IN4920240194", "NSE_EQ|INE389Z07054", "BSE_EQ|INE748A01016", "BSE_EQ|IN000942C036",
"BSE_EQ|INE148I07SM6", "NSE_EQ|INF789F01GV1", "NSE_EQ|INE128A01029", "NSE_EQ|IN2120230197", "NSE_FO|128727",
"NSE_FO|128726", "NSE_FO|128729", "NSE_FO|128728", "BSE_EQ|INE03W107090", "BSE_EQ|INE148I07RY3",
"BSE_EQ|INE651J07689", "BSE_FO|1172370", "BSE_FO|1172372", "BSE_FO|1172375", "NSE_EQ|IN2220230022",
"NSE_EQ|INE508G01029", "NSE_FO|114077", "NSE_FO|114078", "NSE_FO|114079", "NSE_FO|114080", "NSE_FO|114081",
"NSE_FO|38584", "NSE_FO|38585", "NSE_FO|38591", "NSE_FO|38592", "NSE_FO|38599"
]
38 changes: 38 additions & 0 deletions test/sdk_tests/market_basic_v3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import upstox_client
import data_token

configuration = upstox_client.Configuration()
configuration.access_token = data_token.access_token
instruments = data_token.sample_instrument_key
streamer = upstox_client.MarketDataStreamerV3(
upstox_client.ApiClient(configuration), instrumentKeys=instruments[0:70], mode="option_greeks")

streamer.auto_reconnect(True, 5, 10)


def on_open():
print("on open message")


def close(a, b):
print(f"on close message {a}")


def message(data):
print(f"on message message{data}")


def error(er):
print(f"on error message= {er}")


def reconnecting(data):
print(f"reconnecting event= {data}")


streamer.on("open", on_open)
streamer.on("message", message)
streamer.on("close", close)
streamer.on("reconnecting", reconnecting)
streamer.on("error", error)
streamer.connect()
1 change: 1 addition & 0 deletions upstox_client/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
from upstox_client.api.websocket_api import WebsocketApi
# import websocket interfaces into sdk package
from upstox_client.feeder.market_data_streamer import MarketDataStreamer
from upstox_client.feeder.market_data_streamer_v3 import MarketDataStreamerV3
from upstox_client.feeder.portfolio_data_streamer import PortfolioDataStreamer
# import ApiClient
from upstox_client.api_client import ApiClient
Expand Down
Loading

0 comments on commit 1ab5c44

Please sign in to comment.