Skip to content

Commit 3b35a58

Browse files
author
Shanmuganathan
committed
feat: Adding examples folder with websocket implementation samples
1 parent 2ffaf5a commit 3b35a58

File tree

7 files changed

+356
-0
lines changed

7 files changed

+356
-0
lines changed

README.md

+3
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,9 @@ except ApiException as e:
8383
print("Exception when calling ChargeApi->get_brokerage: %s\n" % e)
8484
```
8585

86+
## Examples
87+
88+
[Sample Implementations](examples/README.md) can be found within `/examples`.
8689
## Documentation for API Endpoints
8790

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

examples/README.md

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# PythonSample Implementation
2+
3+
Here are sample implementations of Upstox API features.
4+
5+
## Websocket
6+
7+
### Market stream feed
8+
9+
Python script to connect to the Upstox Websocket API for streaming live market data. It fetches market data for a list of instrument keys and decodes the incoming protobuf data to a JSON format.
10+
11+
[Market updates using Upstox's websocket](websocket/market_data/README.md)
12+
13+
### Porfolio stream feed
14+
15+
Python scripts to connect to the Upstox WebSocket API for streaming live order updates. It fetches the order updates and prints them to the console.
16+
17+
[Order updates using Upstox's websocket](websocket/order_updates/README.md)

examples/websocket/market_data/MarketDataFeed_pb2.py

+55
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
+102
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
# Market Stream feed websocket client
2+
3+
This Python project demonstrates how to connect to the Upstox Websocket API for streaming live market data. It fetches market data for a list of instrument keys and decodes the incoming protobuf data to a JSON format.
4+
5+
## Getting Started
6+
7+
These instructions will help you run the sample websocket client.
8+
9+
### Prerequisites
10+
11+
Before you can run this script, you need to have Python 3.8 or later installed on your system. If you haven't installed Python yet, you can download it from the official website:
12+
13+
[Download Python](https://www.python.org/downloads/)
14+
15+
You will also need to install several Python packages:
16+
17+
- `upstox-python-sdk`
18+
- `websockets`
19+
- `asyncio`
20+
- `protobuf`
21+
22+
You can install these packages using pip, a package manager for Python. Open a terminal and enter the following command:
23+
24+
```sh
25+
pip install upstox-python-sdk websockets asyncio protobuf
26+
```
27+
28+
### Protocol Buffers (Protobuf) Classes Generation
29+
30+
Generate the Protobuf classes in Python from `.proto` file.
31+
32+
Before you can generate the Protobuf classes, you need to download the [proto file](https://assets.upstox.com/feed/market-data-feed/v1/MarketDataFeed.proto) and install the Protocol Buffers compiler (protoc).
33+
34+
To download the Protocol Buffers compiler, go to the [Google Protocol Buffers GitHub repository](https://github.com/protocolbuffers/protobuf/releases) and download the appropriate `protoc-<version>-<os>.zip` file for your operating system. Extract the ZIP file and add the `bin` directory to your system PATH.
35+
36+
For example, on a Unix-like system, you can add the directory to your PATH like this:
37+
38+
```bash
39+
export PATH=$PATH:/path/to/protoc/bin
40+
```
41+
42+
You can confirm that the compiler is correctly installed by opening a new terminal window and running the following command:
43+
44+
```
45+
protoc --version
46+
```
47+
48+
This should print the protoc version.
49+
50+
#### Generate Protobuf classes
51+
52+
Navigate to the directory containing your .proto files and run the following command:
53+
54+
```
55+
protoc --python_out=. *.proto
56+
```
57+
58+
This will generate .py files for each .proto file in the directory.
59+
60+
In your Python code, you can now import the generated classes like any other Python module. For example, if you have a file MarketDataFeed.proto and you've generated MarketDataFeed_pb2.py, you can import it like this:
61+
62+
```
63+
import MarketDataFeed_pb2 as pb
64+
```
65+
66+
Sample class (MarketDataFeed_pb2.py) included as part of this repo.
67+
68+
### Configuration
69+
70+
The script requires an Upstox API access token for authorization. You will need to specify your Upstox API access token in the Python script. Look for the line below and replace 'ACCESS_TOKEN' with your actual access token.
71+
72+
```
73+
configuration.access_token = 'ACCESS_TOKEN'
74+
```
75+
76+
### Running the Script
77+
78+
After installing the prerequisites and setting up your access token, you can run the script. Navigate to the directory containing the script and run the following command:
79+
80+
```
81+
python3 websocket_client.py
82+
```
83+
84+
Replace websocket_client.py with the name of your Python script.
85+
86+
## Understanding the Code
87+
88+
The script first sets up an SSL context and an OAuth2 access token for authorization. It fetches the authorized redirect URI from the Upstox server and uses this to establish a connection to the Websocket server.
89+
90+
The script sends a subscription request for "NSE_INDEX|Nifty Bank" and "NSE_INDEX|Nifty 50". When it receives data from the server, it decodes the protobuf data into a FeedResponse object, converts this object into a dictionary, and then prints the dictionary.
91+
92+
## Support
93+
94+
If you encounter any problems or have any questions about this project, feel free to open an issue in this repository.
95+
96+
## Disclaimer
97+
98+
This is a sample script meant for educational purposes. It may require modifications to work with your specific requirements.
99+
100+
Please replace `'ACCESS_TOKEN'` with your actual access token and `websocket_client.py` with the name of your Python script. Modify any other details as needed to fit your project.
101+
102+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
# Import necessary modules
2+
import asyncio
3+
import json
4+
import ssl
5+
import upstox_client
6+
import websockets
7+
from google.protobuf.json_format import MessageToDict
8+
9+
import MarketDataFeed_pb2 as pb
10+
11+
12+
def get_market_data_feed_authorize(api_version, configuration):
13+
"""Get authorization for market data feed."""
14+
api_instance = upstox_client.WebsocketApi(
15+
upstox_client.ApiClient(configuration))
16+
api_response = api_instance.get_market_data_feed_authorize(api_version)
17+
return api_response
18+
19+
20+
def decode_protobuf(buffer):
21+
"""Decode protobuf message."""
22+
feed_response = pb.FeedResponse()
23+
feed_response.ParseFromString(buffer)
24+
return feed_response
25+
26+
27+
async def fetch_market_data():
28+
"""Fetch market data using WebSocket and print it."""
29+
30+
# Create default SSL context
31+
ssl_context = ssl.create_default_context()
32+
ssl_context.check_hostname = False
33+
ssl_context.verify_mode = ssl.CERT_NONE
34+
35+
# Configure OAuth2 access token for authorization
36+
configuration = upstox_client.Configuration()
37+
38+
api_version = '2.0'
39+
configuration.access_token = 'ACCESS_TOKEN'
40+
41+
# Get market data feed authorization
42+
response = get_market_data_feed_authorize(
43+
api_version, configuration)
44+
45+
# Connect to the WebSocket with SSL context
46+
async with websockets.connect(response.data.authorized_redirect_uri, ssl=ssl_context) as websocket:
47+
print('Connection established')
48+
49+
await asyncio.sleep(1) # Wait for 1 second
50+
51+
# Data to be sent over the WebSocket
52+
data = {
53+
"guid": "someguid",
54+
"method": "sub",
55+
"data": {
56+
"mode": "full",
57+
"instrumentKeys": ["NSE_INDEX|Nifty Bank", "NSE_INDEX|Nifty 50"]
58+
}
59+
}
60+
61+
# Convert data to binary and send over WebSocket
62+
binary_data = json.dumps(data).encode('utf-8')
63+
await websocket.send(binary_data)
64+
65+
# Continuously receive and decode data from WebSocket
66+
while True:
67+
message = await websocket.recv()
68+
decoded_data = decode_protobuf(message)
69+
70+
# Convert the decoded data to a dictionary
71+
data_dict = MessageToDict(decoded_data)
72+
73+
# Print the dictionary representation
74+
print(json.dumps(data_dict))
75+
76+
77+
# Execute the function to fetch market data
78+
asyncio.run(fetch_market_data())
+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# Portfolio Stream Feed WebSocket Client
2+
3+
This Python project demonstrates how to connect to the Upstox WebSocket API for streaming live order updates. It fetches the order updates and prints them to the console.
4+
5+
## Getting Started
6+
7+
These instructions will help you run the sample websocket client.
8+
9+
### Prerequisites
10+
11+
Before you can run this script, you need to have Python 3.8 or later installed on your system. If you haven't installed Python yet, you can download it from the official website:
12+
13+
[Download Python](https://www.python.org/downloads/)
14+
15+
You will also need to install several Python packages:
16+
17+
- `upstox-python-sdk`
18+
- `websockets`
19+
- `asyncio`
20+
21+
You can install these packages using pip, a package manager for Python. Open a terminal and enter the following command:
22+
23+
```sh
24+
pip install upstox-python-sdk websockets asyncio
25+
```
26+
27+
### Configuration
28+
29+
The script requires an Upstox API access token for authorization. You will need to specify your Upstox API access token in the Python script. Look for the line below and replace 'ACCESS_TOKEN' with your actual access token.
30+
31+
```
32+
configuration.access_token = 'ACCESS_TOKEN'
33+
```
34+
35+
### Running the Script
36+
37+
After installing the prerequisites and setting up your access token, you can run the script. Navigate to the directory containing the script and run the following command:
38+
39+
```
40+
python3 websocket_client.py
41+
```
42+
43+
Replace websocket_client.py with the name of your Python script.
44+
45+
## Understanding the Code
46+
47+
The script first sets up an SSL context and an OAuth2 access token for authorization. It fetches the authorized redirect URI from the Upstox server and uses this to establish a connection to the WebSocket server.
48+
49+
The script then enters a loop, where it continually receives order update messages from the server and prints them to the console..
50+
51+
## Support
52+
53+
If you encounter any problems or have any questions about this project, feel free to open an issue in this repository.
54+
55+
## Disclaimer
56+
57+
This is a sample script meant for educational purposes. It may require modifications to work with your specific requirements.
58+
59+
Please replace `'ACCESS_TOKEN'` with your actual access token and `websocket_client.py` with the name of your Python script. Modify any other details as needed to fit your project.
60+
61+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
from __future__ import print_function
2+
import upstox_client
3+
import ssl
4+
import websockets
5+
import asyncio
6+
import json
7+
8+
9+
def get_portfolio_stream_feed_authorize(api_version, configuration):
10+
api_instance = upstox_client.WebsocketApi(
11+
upstox_client.ApiClient(configuration))
12+
api_response = api_instance.get_portfolio_stream_feed_authorize(
13+
api_version)
14+
return api_response
15+
16+
17+
async def fetch_order_updates():
18+
ssl_context = ssl.create_default_context()
19+
ssl_context.check_hostname = False
20+
ssl_context.verify_mode = ssl.CERT_NONE
21+
22+
# Configure OAuth2 access token for authorization: OAUTH2
23+
configuration = upstox_client.Configuration()
24+
25+
api_version = '2.0'
26+
configuration.access_token = 'ACCESS_TOKEN'
27+
28+
# Get portfolio stream feed authorize
29+
response = get_portfolio_stream_feed_authorize(
30+
api_version, configuration)
31+
32+
async with websockets.connect(response.data.authorized_redirect_uri, ssl=ssl_context) as websocket:
33+
print('Connection established')
34+
35+
# Perform WebSocket operations
36+
while True:
37+
message = await websocket.recv()
38+
print(json.dumps(message))
39+
40+
asyncio.run(fetch_order_updates())

0 commit comments

Comments
 (0)