LTP Quotes for Indices not working

Hi, in the instruments file (complete.csv, nse.csv etc) the field values for tradingsymbol column are missing. I can’t seem to fetch the LTP of “Bank Nifty” for example, I have tried “NSE_INDEX|Bank Nifty”, “Bank Nifty”, “NSE_INDEX|28”, “28”, it just keeps saying symbol is of invalid format. What’s the issue? This is a very basic thing.

I am using this exact code for LTP: https://github.com/upstox/upstox-python/blob/master/docs/MarketQuoteApi.md#ltp

This is what I keep getting:

Reading instruments from file…
NSE_INDEX|Nifty Bank
idx_ltp: 0. error: Exception when calling MarketQuoteApi->ltp: (400)
Reason: Bad Request
HTTP response headers: HTTPHeaderDict({‘Date’: ‘Sat, 23 Sep 2023 13:46:11 GMT’, ‘Content-Type’: ‘application/json’, ‘Transfer-Encoding’: ‘chunked’, ‘Connection’: ‘keep-alive’, ‘Vary’: ‘Origin, Access-Control-Request-Method, Access-Control-Request-Headers’, ‘message’: ‘request failed’, ‘requestId’: ‘b5e887cf-0d23-4c30-952a-90cc293245e3’, ‘X-Content-Type-Options’: ‘nosniff’, ‘X-XSS-Protection’: ‘1; mode=block’, ‘Cache-Control’: ‘no-cache, no-store, max-age=0, must-revalidate’, ‘Pragma’: ‘no-cache’, ‘Expires’: ‘0’, ‘Strict-Transport-Security’: ‘max-age=0; includeSubDomains’, ‘X-Frame-Options’: ‘DENY’, ‘CF-Cache-Status’: ‘DYNAMIC’, ‘Set-Cookie’: ‘_cfuvid=wTrqc4Gyakcdl6kj2f9k_pTCE2c8yHS_TTUfCJzDj2s-1695476771394-0-604800000; path=/; domain=.upstox.com; HttpOnly; Secure; SameSite=None’, ‘Server’: ‘cloudflare’, ‘CF-RAY’: ‘80b33b7d0ad6470a-BOM’})
HTTP response body: b’{“status”:“error”,“errors”:[{“errorCode”:“UDAPI1011”,“message”:“symbol is of invalid format”,“propertyPath”:“getLastTradedPrice.symbol”,“invalidValue”:“NSE_INDEX|Nifty Bank,”,“error_code”:“UDAPI1011”,“property_path”:“getLastTradedPrice.symbol”,“invalid_value”:“NSE_INDEX|Nifty Bank,”}]}’

The same issue is with your history api, if we try that as alternative, it doesn’t recognize the index’s instrument_key or tradingsymbol, no matter you put it in a list or prepare it as a comma-separated string:

D:\strategyu>python test1.py

Reading instruments from file…
NSE_INDEX|Nifty Bank
idx_ltp: 0. error: Exception when calling HistoryApi->get_intra_day_candle_data: (400)
Reason: Bad Request
HTTP response headers: HTTPHeaderDict({‘Date’: ‘Sat, 23 Sep 2023 19:20:09 GMT’, ‘Content-Type’: ‘application/json’, ‘Transfer-Encoding’: ‘chunked’, ‘Connection’: ‘keep-alive’, ‘Vary’: ‘Origin, Access-Control-Request-Method, Access-Control-Request-Headers’, ‘message’: ‘request failed’, ‘requestId’: ‘8a11ba90-316a-4ef6-bff3-420bfd5cf604’, ‘X-Content-Type-Options’: ‘nosniff’, ‘X-XSS-Protection’: ‘1; mode=block’, ‘Cache-Control’: ‘no-cache, no-store, max-age=0, must-revalidate’, ‘Pragma’: ‘no-cache’, ‘Expires’: ‘0’, ‘Strict-Transport-Security’: ‘max-age=0; includeSubDomains’, ‘X-Frame-Options’: ‘DENY’, ‘CF-Cache-Status’: ‘MISS’, ‘Set-Cookie’: ‘_cfuvid=wjPcE3GQKjqQokKSBhozaEZFDgD_MLVGT5d3EogvG4E-1695496809931-0-604800000; path=/; domain=.upstox.com; HttpOnly; Secure; SameSite=None’, ‘Server’: ‘cloudflare’, ‘CF-RAY’: ‘80b524b5ea323b37-BOM’})
HTTP response body: b’{“status”:“error”,“errors”:[{“errorCode”:“UDAPI1021”,“message”:“Instrument key is of invalid format”,“propertyPath”:“getIntraDayCandleData.instrumentKey”,“invalidValue”:“['NSE_INDEX|Nifty Bank']”,“error_code”:“UDAPI1021”,“property_path”:“getIntraDayCandleData.instrumentKey”,“invalid_value”:“['NSE_INDEX|Nifty Bank']”}]}’

D:\strategyu>python test1.py

Reading instruments from file…
NSE_INDEX|Nifty Bank,
idx_ltp: 0. error: Exception when calling HistoryApi->get_intra_day_candle_data: (400)
Reason: Bad Request
HTTP response headers: HTTPHeaderDict({‘Date’: ‘Sat, 23 Sep 2023 19:20:55 GMT’, ‘Content-Type’: ‘application/json’, ‘Transfer-Encoding’: ‘chunked’, ‘Connection’: ‘keep-alive’, ‘Vary’: ‘Origin, Access-Control-Request-Method, Access-Control-Request-Headers’, ‘message’: ‘request failed’, ‘requestId’: ‘d4df74c2-8240-4a18-b967-d7f644dcf0df’, ‘X-Content-Type-Options’: ‘nosniff’, ‘X-XSS-Protection’: ‘1; mode=block’, ‘Cache-Control’: ‘no-cache, no-store, max-age=0, must-revalidate’, ‘Pragma’: ‘no-cache’, ‘Expires’: ‘0’, ‘Strict-Transport-Security’: ‘max-age=0; includeSubDomains’, ‘X-Frame-Options’: ‘DENY’, ‘CF-Cache-Status’: ‘MISS’, ‘Set-Cookie’: ‘_cfuvid=rqNqR52tJJnoz64iXNCNMr1hiRgFMdlN_4.LMfgQQi4-1695496855879-0-604800000; path=/; domain=.upstox.com; HttpOnly; Secure; SameSite=None’, ‘Server’: ‘cloudflare’, ‘CF-RAY’: ‘80b525d51c801bca-BOM’})
HTTP response body: b’{“status”:“error”,“errors”:[{“errorCode”:“UDAPI1021”,“message”:“Instrument key is of invalid format”,“propertyPath”:“getIntraDayCandleData.instrumentKey”,“invalidValue”:“NSE_INDEX|Nifty Bank,”,“error_code”:“UDAPI1021”,“property_path”:“getIntraDayCandleData.instrumentKey”,“invalid_value”:“NSE_INDEX|Nifty Bank,”}]}’

@Sheoran

The sample code provided in the documentation appears to be functioning correctly on our end. You can see this illustrated in the attached screenshot.

The issue might be specific to your local environment or code. Kindly review and try running it again.

Thanks!!

Ok, it seems the error was because your API is returning different values for the same symbol, as it clear from your own screenshot as well. Why is the symbol “NSE_INDEX|Nifty Bank” being returned as “NSE_INDEX:Nifty Bank”? It should be a vertical bar (|) and not a colon (:). Please check and rectify, it seems to be a bug in your API.

Should be returning “NSE_Index|Nifty Bank” and not “NSE_Index:Nifty Bank”.

def get_ltp(self, symbol):
try:
api_response = self.api_instance_ltp.ltp(symbol, api_version=self.upstox_api_version)
print(api_response)
except ApiException as e:
print(“Exception when calling MarketQuoteApi->ltp: %s\n” % e)

{‘data’: {‘NSE_INDEX:Nifty Bank’: {‘instrument_token’: ‘NSE_INDEX|Nifty Bank’,
‘last_price’: 44758.3}},
‘status’: ‘success’}

The error ‘UDAPI1021’ you previously highlighted is user-caused. The problem stemmed from an extra comma at the end of the instrument_key value you provided. Now that this has been rectified, and you’re receiving successful API responses, you’ve brought up a new concern. Please note, the format of the response you’re receiving is designed with intent. We’ll relay your feedback to our team.

Thank you for your understanding and cooperation!

Shanmugam, please don’t take it personal, it’s your job to keep your systems error-free.

How is someone going to know that you are also generating the “NSE_Index:Nifty Bank” symbol in response to a user feeding in “NSE_Index|Nifty Bank"? If you say it’s by design, it doesn’t seem to be documented anywhere in your docs. Because when we are going to check for response.data.{symbol}.last_price, we are not going to find it.

Also, your APIs don’t return a dict and the object returned resists being cast to dict, I am having to implement a workaround for getting a simple LTP via API. If you return a dict instead or a dict castable object (for your api_response), it would be as simple as fetching api_response[‘data’][symbol][‘last_price’]. Right now, is there a better way than doing this?:

def get_ltp(self, symbol):
    symbol_variation = symbol.replace('|', ':')
    try:
        response = self.api_instance_ltp.ltp(symbol, api_version=self.upstox_api_version)
        if response.status == 'success':
            rkey = ""
            rval = ""
            for key, val in response.data.items():
                if str(key) in [symbol, symbol_variation]:
                    rkey = str(key)
                    rval = vars(val)
                    break
            if '_last_price' in rval: return (float(rval['_last_price']), "")
            else: return (0, "missing key error: last_price")
    except Exception as e:
        return (0, "Exception when calling MarketQuoteApi->ltp: %s\n" % e)

We sincerely value your suggestions, feedback, and your keen interest in the Upstox API. We will incorporate the mentioned details into our upcoming documentation release.

As said in the last thread will relay your feedback to the team. As part of our internal audit process, we assess recommended enhancements from our clients and prioritize those that will facilitate seamless integration for a broader customer base.