Hi Team,
I’m having some trouble with the Market Feed API. I’m trying to subscribe to a new symbol, but I’m running into an error. Could you help me resolve this issue?
Code:
def update_websocket_subscriptions(stock):
global websocket_feed
if websocket_feed:
with websocket_lock:
exchange = marketfeed.NSE
token = str(token_lookup(stock))
feed_type = marketfeed.Ticker
try:
# Create a list of tuples for each subscription, without feed_type
symbols = [(exchange, token)]
print(f"Attempting to subscribe with symbols: {
symbols}, feed_request_code: {feed_type}")
# Pass the symbols list and feed_request_code as separate arguments
websocket_feed.subscribe_symbols(symbols, feed_type)
logger.info(
f"Updated WebSocket subscription for stock: {stock}")
except Exception as e:
logger.error(
f"Error updating WebSocket subscription: {str(e)}")
logger.error(f"Error type: {type(e).__name__}")
logger.error(f"Error args: {e.args}")
async def monitor_positions(client_id, access_token):
global websocket_feed
def on_message(message):
data = json.loads(message)
with websocket_lock:
for stock, limits in list(trading_signals.items()):
if data['symbol'] == stock:
current_price = data['ltp']
if (limits['transaction_type'] == 'BUY' and current_price >= limits['target']) or \
(limits['transaction_type'] == 'SELL' and current_price <= limits['target']):
cancelPosition(stock)
send_slack_notification(f"Target reached for {
stock}. Position closed.")
del trading_signals[stock]
elif (limits['transaction_type'] == 'BUY' and current_price <= limits['stop_loss']) or \
(limits['transaction_type'] == 'SELL' and current_price >= limits['stop_loss']):
cancelPosition(stock)
send_slack_notification(
f"Stop-loss triggered for {stock}. Position closed.")
del trading_signals[stock]
try:
# Initial setup with empty instruments list
websocket_feed = marketfeed.DhanFeed(
client_id,
access_token,
[], # Start with an empty list of instruments
marketfeed.Ticker
)
# Set the message handler
websocket_feed.on_message = on_message
# Run the WebSocket connection
await websocket_feed.connect()
await websocket_feed.run_forever()
except Exception as e:
logger.error(f"Error setting up WebSocket connection: {str(e)}")