Changed the nse_quote_ltp() function

So, NSEPython breaks for nsequote function for niftyfin futures. Aparrently I never thought futures and options expiry will be different for same instrument.

Also I have coded like a monosyllabic fuck. See how I have hardcoded indices like a noob. How this will be passive income if NSE keeps actively monitoring it!!! and it does not autoadapt

Here is new version

def nse_quote_ltp(symbol,expiryDate="latest",optionType="-",strikePrice=0):
  payload = nse_quote(symbol)
  print(payload)

  meta = "Options"
  if(optionType=="Fut"): meta = "Futures"
  if(optionType=="PE"):optionType="Put"
  if(optionType=="CE"):optionType="Call"

  if(expiryDate=="latest") or (expiryDate=="next"):

    print(payload["expiryDatesByInstrument"]["Index Futures"][0])
    if(meta=="Futures"):
      selected_key = next((key for key in payload["expiryDatesByInstrument"] if "futures" in key.lower()), None)
    if(meta=="Options"):
      selected_key = next((key for key in payload["expiryDatesByInstrument"] if "options" in key.lower()), None)

    if(expiryDate=="latest"): expiryDate=payload["expiryDatesByInstrument"][selected_key][0]
    if(expiryDate=="next"): expiryDate=payload["expiryDatesByInstrument"][selected_key][1]
  

  if(optionType!="-"):
      for i in payload['stocks']:
        if meta in i['metadata']['instrumentType']:
          #print(i['metadata'])
          if(optionType=="Fut"):
              if(i['metadata']['expiryDate']==expiryDate):
                lastPrice = i['metadata']['lastPrice']

          if((optionType=="Put")or(optionType=="Call")):
              if (i['metadata']["expiryDate"]==expiryDate):
                if (i['metadata']["optionType"]==optionType):
                  if (i['metadata']["strikePrice"]==strikePrice):
                    #print(i['metadata'])
                    lastPrice = i['metadata']['lastPrice']

  if(optionType=="-"):
      lastPrice = payload['underlyingValue']

  return lastPrice

So stock futures or index futures. both has the word “futures” right? why not use that logic ?

example collab → nsepythonserver/examples/nse_quote_ltp()_upgrade.ipynb at main · aeron7/nsepythonserver · GitHub

Modifed

def nse_optionchain_ltp(payload,strikePrice,optionType,inp=0,intent=""):
    expiryDate=payload['records']['expiryDates'][inp]
    for x in range(len(payload['records']['data'])):
      if((payload['records']['data'][x]['strikePrice']==strikePrice) & (payload['records']['data'][x]['expiryDate']==expiryDate)):
          if(intent==""): return payload['records']['data'][x][optionType]['lastPrice']
          if(intent=="sell"): return payload['records']['data'][x][optionType]['bidprice']
          if(intent=="buy"): return payload['records']['data'][x][optionType]['askPrice']

Second the variable payload has they key value

“expiryDates”:[
“26-Sep-2023”,
“03-Oct-2023”,
“10-Oct-2023”,
“17-Oct-2023”,
“23-Oct-2023”,
“31-Oct-2023”,
“28-Nov-2023”
]

Now I want to print payload[“expiryDates”] only with dates that are of greater than equal to today

But if you do things are middle of night of Thursday, You will tear your hairs off!

correct is

def nse_optionchain_ltp(payload,strikePrice,optionType,inp=0,intent=""):
    expiry_dates = payload['records']['expiryDates']
    expiry_dates = [datetime.datetime.strptime(date, "%d-%b-%Y") for date in expiry_dates]
    expiry_dates = [date.strftime("%d-%b-%Y") for date in expiry_dates if date >= datetime.datetime.now()]

    expiryDate=expiry_dates[inp]
    for x in range(len(payload['records']['data'])):
      if((payload['records']['data'][x]['strikePrice']==strikePrice) & (payload['records']['data'][x]['expiryDate']==expiryDate)):
          if(intent==""): return payload['records']['data'][x][optionType]['lastPrice']
          if(intent=="sell"): return payload['records']['data'][x][optionType]['bidprice']
          if(intent=="buy"): return payload['records']['data'][x][optionType]['askPrice']

Same with

def nse_expirydetails(payload,i=0):
    currentExpiry = payload['records']['expiryDates'][i]
    currentExpiry = datetime.datetime.strptime(currentExpiry,'%d-%b-%Y').date()  # converting json datetime to alice datetime
    date_today = run_time.strftime('%Y-%m-%d')  # required to remove hh:mm:ss
    date_today = datetime.datetime.strptime(date_today,'%Y-%m-%d').date()
    dte = (currentExpiry - date_today).days
    return currentExpiry,dte

Changed to

def nse_expirydetails(payload,i=0):

    expiry_dates = payload['records']['expiryDates']
    expiry_dates = [datetime.datetime.strptime(date, "%d-%b-%Y") for date in expiry_dates]
    expiry_dates = [date.strftime("%d-%b-%Y") for date in expiry_dates if date >= datetime.datetime.now()]

    currentExpiry=expiry_dates[i]    
    currentExpiry = datetime.datetime.strptime(currentExpiry,'%d-%b-%Y').date()  # converting json datetime to alice datetime
    date_today = run_time.strftime('%Y-%m-%d')  # required to remove hh:mm:ss
    date_today = datetime.datetime.strptime(date_today,'%Y-%m-%d').date()
    dte = (currentExpiry - date_today).days
    return currentExpiry,dte
def nse_optionchain_ltp(payload,strikePrice,optionType,inp=0,intent=""):
    expiry_dates = payload['records']['expiryDates']
    expiry_dates = [datetime.datetime.strptime(date, "%d-%b-%Y") for date in expiry_dates]
    expiry_dates = [date.strftime("%d-%b-%Y") for date in expiry_dates if date >= datetime.datetime.now()]
    expiryDate=expiry_dates[inp]
    for x in range(len(payload['records']['data'])):
      if((payload['records']['data'][x]['strikePrice']==strikePrice) & (payload['records']['data'][x]['expiryDate']==expiryDate)):
          if(intent==""): return payload['records']['data'][x][optionType]['lastPrice']
          if(intent=="sell"): return payload['records']['data'][x][optionType]['bidprice']
          if(intent=="buy"): return payload['records']['data'][x][optionType]['askPrice']

def nse_expirydetails(payload,i=0):  #Can make problem. Use nse_expirydetails_by_symbol()

    expiry_dates = payload['records']['expiryDates']
    expiry_dates = [datetime.datetime.strptime(date, "%d-%b-%Y") for date in expiry_dates]
    expiry_dates = [date.strftime("%d-%b-%Y") for date in expiry_dates if date >= datetime.datetime.now()]
    currentExpiry=expiry_dates[i]    
    currentExpiry = datetime.datetime.strptime(currentExpiry,'%d-%b-%Y').date()  # converting json datetime to alice datetime
    date_today = run_time.strftime('%Y-%m-%d')  # required to remove hh:mm:ss
    date_today = datetime.datetime.strptime(date_today,'%Y-%m-%d').date()
    dte = (currentExpiry - date_today).days
    return currentExpiry,dte

def nse_quote_ltp(symbol,expiryDate="latest",optionType="-",strikePrice=0):
  payload = nse_quote(symbol)

  meta = "Options"
  if(optionType=="Fut"): meta = "Futures"
  if(optionType=="PE"):optionType="Put"
  if(optionType=="CE"):optionType="Call"

  if(expiryDate=="latest") or (expiryDate=="next"):

    if(meta=="Futures"):
      selected_key = next((key for key in payload["expiryDatesByInstrument"] if "futures" in key.lower()), None)
    if(meta=="Options"):
      selected_key = next((key for key in payload["expiryDatesByInstrument"] if "options" in key.lower()), None)

    expiry_dates=payload["expiryDatesByInstrument"][selected_key]
    expiry_dates = [datetime.datetime.strptime(date, "%d-%b-%Y") for date in expiry_dates]
    expiry_dates = [date.strftime("%d-%b-%Y") for date in expiry_dates if date >= datetime.datetime.now()]
    if(expiryDate=="latest"): expiryDate=expiry_dates[0]
    if(expiryDate=="next"): expiryDate=expiry_dates[1]
  

  if(optionType!="-"):
      for i in payload['stocks']:
        if meta in i['metadata']['instrumentType']:
          #print(i['metadata'])
          if(optionType=="Fut"):
              if(i['metadata']['expiryDate']==expiryDate):
                lastPrice = i['metadata']['lastPrice']

          if((optionType=="Put")or(optionType=="Call")):
              if (i['metadata']["expiryDate"]==expiryDate):
                if (i['metadata']["optionType"]==optionType):
                  if (i['metadata']["strikePrice"]==strikePrice):
                    #print(i['metadata'])
                    lastPrice = i['metadata']['lastPrice']

  if(optionType=="-"):
      lastPrice = payload['underlyingValue']

  return lastPrice

def nse_expirydetails_by_symbol(symbol,meta ="Futures",i=0):
    payload = nse_quote(symbol)

    if(meta=="Futures"):
      selected_key = next((key for key in payload["expiryDatesByInstrument"] if "futures" in key.lower()), None)
    if(meta=="Options"):
      selected_key = next((key for key in payload["expiryDatesByInstrument"] if "options" in key.lower()), None)

    expiry_dates=payload["expiryDatesByInstrument"][selected_key]
    expiry_dates = [datetime.datetime.strptime(date, "%d-%b-%Y") for date in expiry_dates]
    expiry_dates = [date.strftime("%d-%b-%Y") for date in expiry_dates if date >= datetime.datetime.now()]
    
    currentExpiry=expiry_dates[i]
    currentExpiry = datetime.datetime.strptime(currentExpiry,'%d-%b-%Y').date()    
    dte = (currentExpiry - datetime.datetime.now().date()).days
    return currentExpiry,dte

Version 2.5 Updated with the above changes

Again updated the piece of shit code.

Replaced

expiry_dates = [datetime.datetime.strptime(date, "%d-%b-%Y").date() for date in expiry_dates]    
expiry_dates = [date.strftime("%d-%b-%Y") for date in expiry_dates if date >= today_date]

In your code, I was parsing the dates in the ‘expiry_dates’ list using the format “%d-%b-%Y,” which results in dates like ‘21-Sep-2023.’ However, when you compare them to datetime.datetime.now(), you are comparing a datetime object with a date object, and the comparison might not work as expected due to differences in precision.

My code deleted today’s expiry right after the market time which is fucked up. It should do that post 12:00 midnight.

Version 2.6 Updated with the above changes.