It looks like you're new here. If you want to get involved, click one of these buttons!
def on_ticks(ws, ticks):
for tick in ticks:
myTicks.append(tick)
live_data.append(tick)
# function to subscribe the instruments. Instrument list is based on the selection made by the user
def on_connect(ws, repsonse):
ws.subscribe(subscribetokens)
ws.set_mode(ws.MODE_FULL, subscribetokens)
# Function to check error msg
def on_error(ws, code, reason):
logging.info(
"Connection error: {code} - {reason}".format(code=code, reason=reason))
# function to check recconect msg
def on_reconnect(ws, attempts_count):
logging.info("Reconnecting: {}".format(attempts_count))
# Function to read the atm values based on user input
@app.route("/ATMValue")
def ATMValue():
kite = connect()
userInput = json.loads(request.args.get('payload'))
instrument = userInput['instrument']
expiryDate = userInput['expiryDate']
atm_count = userInput['atmValue']
dateValue = expiryDate
date_object = datetime.strptime(dateValue, "%d-%m-%Y").date()
# Define instrument-specific settings
if instrument == KiteSettings.NIFTY_TEXT:
index_value = KiteSettings.NIFTY_INDEX_VALUE
strike_price_interval = KiteSettings.instrument_increment_nifty
elif instrument == KiteSettings.BANKNIFTY_TEXT:
index_value = KiteSettings.BANKNIFTY_INDEX_VALUE
strike_price_interval = KiteSettings.instrument_increment_bank
elif instrument == KiteSettings.FINNIFTY_TEXT:
index_value = KiteSettings.FINNIFTY_INDEX_VALUE
strike_price_interval = KiteSettings.instrument_increment_fin
elif instrument == KiteSettings.MIDCAP_TEXT:
index_value = KiteSettings.MIDCAP_INDEX_VALUE
strike_price_interval = KiteSettings.instrument_increment_midcap
elif instrument == KiteSettings.SENSEX_TEXT:
index_value = KiteSettings.SENSEX_INDEX_VALUE
strike_price_interval = KiteSettings.instrument_increment_sensex
else:
raise ValueError("Invalid instrument type")
# Get the current strike price
nifty_instruments = kite.quote(index_value)
current_strike_price = nifty_instruments[index_value]["last_price"]
# Get the ATM strike price
atm_strike_price = round(current_strike_price / 100) * 100
# Fetch instrument dump for the specified expiry date and instrument type
instrument_dump = []
instrument_df = []
instrument_dump = kite.instruments("NFO")
if instrument == KiteSettings.SENSEX_TEXT:
instrument_dump = kite.instruments("BFO")
instrument_df = pd.DataFrame(instrument_dump)
instrument_df.to_csv("ALL_Instruments.csv", index=False)
instrument_df = pd.DataFrame(instrument_dump)
filtered_df = instrument_df[(pd.to_datetime(instrument_df['expiry']).dt.date == date_object) &
(instrument_df['tradingsymbol'].str.contains(instrument))]
# Fetch ATM values above and below current Nifty index
atm_values = []
for i in range(atm_count, 0, -1):
strike_price_above = round(
atm_strike_price + (i * strike_price_interval))
strike_price_below = round(
atm_strike_price - (i * strike_price_interval))
atm_values.append(strike_price_above)
atm_values.append(strike_price_below)
atm_values.append(atm_strike_price)
# Sort the atm_values array in descending order
atm_values.sort(reverse=True)
# Filter instruments based on strike price and instrument type
ce_instruments = []
pe_instruments = []
for quote in atm_values:
ce_instrument = filtered_df[(filtered_df['strike'] == quote) &
(filtered_df['instrument_type'] == 'CE')]
pe_instrument = filtered_df[(filtered_df['strike'] == quote) &
(filtered_df['instrument_type'] == 'PE')]
if not ce_instrument.empty:
ce_instruments.append(ce_instrument.to_dict(orient='records')[0])
isntrument_token.append(int(ce_instrument.to_dict(
orient='records')[0]["instrument_token"]))
if not pe_instrument.empty:
pe_instruments.append(pe_instrument.to_dict(orient='records')[0])
isntrument_token.append(int(pe_instrument.to_dict(
orient='records')[0]["instrument_token"]))
# check for the subscribed token with allready subscribed tokens
for token in isntrument_token:
if token not in subscribetokens:
subscribetokens.append(int(token))
# print("sub token",subscribetokens)
try:
time.sleep(2)
kws = KiteTicker(KiteSettings.api_key,
KiteSettings.access_token, reconnect=True)
kws.on_ticks = on_ticks
kws.on_connect = on_connect
kws.on_error = on_error
kws.on_reconnect = on_reconnect
kws.connect(threaded=True)
time.sleep(2)
except:
print("error in in socket connection")
# print(atm_values.sort(reverse = True))
# Create a dictionary to hold the CE and PE instruments
result = {
'atm_values': atm_values,
'ce_instruments': ce_instruments,
'pe_instruments': pe_instruments
}
# Convert the dictionary to a JSON object
json_result = json.dumps(result, default=str)
return json_result