I have the following code below, with which I am simply getting the feed for data and trying to place order. I have used this same API in non web socket python code to place order and it always works, could you tell why it fails and what is the solution
Import necessary modules
import asyncio
import json
import ssl
import upstox_client
import websockets
from google.protobuf.json_format import MessageToDict
from threading import Thread
import MarketDataFeed_pb2 as pb
from time import sleep
import myFuncs as samfilename =f"/Users/sameer/Documents/Personal_learning/myPython/access_token.txt"
with open(filename,“r”) as file:
access_token = file.read().strip(‘\n’)def get_market_data_feed_authorize(api_version, configuration):
“”“Get authorization for market data feed.”“”
api_instance = upstox_client.WebsocketApi(
upstox_client.ApiClient(configuration))
api_response = api_instance.get_market_data_feed_authorize(api_version)
return api_responsedef decode_protobuf(buffer):
“”“Decode protobuf message.”“”
feed_response = pb.FeedResponse()
feed_response.ParseFromString(buffer)
return feed_responseasync def fetch_market_data():
global data_dict
“”“Fetch market data using WebSocket and print it.”“”# Create default SSL context ssl_context = ssl.create_default_context() ssl_context.check_hostname = False ssl_context.verify_mode = ssl.CERT_NONE # Configure OAuth2 access token for authorization configuration = upstox_client.Configuration() api_version = '2.0' configuration.access_token = access_token # Get market data feed authorization response = get_market_data_feed_authorize( api_version, configuration) # Connect to the WebSocket with SSL context async with websockets.connect(response.data.authorized_redirect_uri, ssl=ssl_context) as websocket: print('Connection established') await asyncio.sleep(1) # Wait for 1 second # Data to be sent over the WebSocket data = { "guid": "someguid", "method": "sub", "data": { "mode": "full", "instrumentKeys": ["NSE_INDEX|Nifty Bank", "NSE_INDEX|Nifty 50", "NSE_INDEX|India VIX", "NSE_INDEX|Nifty IT"] } } # Convert data to binary and send over WebSocket binary_data = json.dumps(data).encode('utf-8') await websocket.send(binary_data) # Continuously receive and decode data from WebSocket while True: message = await websocket.recv() decoded_data = decode_protobuf(message) # Convert the decoded data to a dictionary data_dict = MessageToDict(decoded_data) # Print the dictionary representation # print(json.dumps(data_dict))
Execute the function to fetch market data
asyncio.run(fetch_market_data())
def run_websocket():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(fetch_market_data())
#sleep(0.5)
Start the WebSocket connection in a separate thread
websocket_thread = Thread(target=run_websocket)
websocket_thread.start()sleep(1)
while True:
sleep(1)
ltp = data_dict[‘feeds’][‘NSE_INDEX|Nifty Bank’][‘ff’][‘indexFF’][‘ltpc’][‘ltp’]
ltp_50 = data_dict[‘feeds’][‘NSE_INDEX|Nifty 50’][‘ff’][‘indexFF’][‘ltpc’][‘ltp’]
ltp_vix = data_dict[‘feeds’][‘NSE_INDEX|India VIX’][‘ff’][‘indexFF’][‘ltpc’][‘ltp’]
print(f"Last Price {ltp} : {ltp_50} : {ltp_vix}")
sam.place_entry_order(‘NSE_FO|65514’, 25, access_token)
#print("hello")
the place_entry_order function is as below:
def place_entry_order(instrument, quantity, access_token):
url = 'https://api.upstox.com/v2/order/place' headers = { 'Content-Type': 'application/json', 'Accept': 'application/json', 'Authorization': access_token, } data = { 'quantity': quantity, 'product': 'I', 'validity': 'DAY', 'price': 0, 'tag': 'string', 'instrument_token': instrument, 'order_type': 'MARKET', 'transaction_type': 'SELL', 'disclosed_quantity': 0, 'trigger_price': 0, 'is_amo': False, } try: # Send the POST request response = requests.post(url, json=data, headers=headers) # Print the response status code and body print('Response Code:', response.status_code) print('Response Body:', response.json()) except Exception as e: # Handle exceptions print('Error:', str(e)) return response.json()