I’m having some trouble with the Market Feed API

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)}")

Hello @Raj27

Will require explanation of this code to help you out. Why not use subscribe_symbols function instead, which is on the library, to get help with this?

Hi @Hardik

I’m trying to follow the documentation, but I’m getting an error: DhanFeed.__init__() missing 1 required positional argument: 'subscription_code'. Could you help me figure out how to resolve this issue?"

Hello @Raj27

Can you check if you have updated the library to v1.4?

Hi @Hardik,

I just upgraded the library, but it’s showing version 1.3.2 instead of 1.4. I’m not sure if that’s correct or not, but it seems our original problem is resolved. However, I’ve run into another issue — as you can see in the image below, I’m not getting any data.

Could you help me sort this out?

Hello @Raj27

Apologies from my end, it should be 1.3.2 itself. Can you tell me which instrument is this which you have subscribed to?

Hi there! Thank you so much for your assistance. I’m still a beginner and have a question. When I start the instrument, it provides market data continuously, but if I want to add more symbols while the code is already running, how can I do that?

@Hardik : Im using the Than Market Feed Api. However for MCX, say CRUDEOIL 5800 CE, Im not getting the OI data. It is returning the quote data successfully, however, I don’t see the OI data there!

I got only the quote packet which does not include OI data. - {‘type’: ‘Quote Data’, ‘exchange_segment’: 5, ‘security_id’: 435850, ‘LTP’: ‘55.10’, ‘LTQ’: 1, ‘LTT’: ‘20:17:32’, ‘avg_price’: ‘84.81’, ‘volume’: 249851, ‘total_sell_quantity’: 5854, ‘total_buy_quantity’: 1435, ‘open’: ‘65.00’, ‘close’: ‘59.10’, ‘high’: ‘109.00’, ‘low’: ‘52.80’}

Hello @Raj27 @Vineet_Kum

You can use subscribe_symbols function to add more instruments while the connection is open

OI Data is sent in separate packet as and when OI is updated. You can find it under documentation : here.