import requests
Access Token obtained after successful authorization
access_token = open(‘access_token.txt’, ‘r’).read().strip()
URLs for fetching Option Chain data
url_bnf = ‘https://api.upstox.com/v2/option_chain?symbol=BANKNIFTY’
url_nf = ‘https://api.upstox.com/v2/option_chain?symbol=NIFTY’
def get_oi_data(url):
headers = {
‘accept’: ‘application/json’,
‘Api-Version’: ‘2.0’,
‘Authorization’: f’Bearer {access_token}’
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.json()
else:
print(f"Failed to fetch data. Status Code: {response.status_code}")
return None
def store_oi_data(url, symbol):
oi_data = get_oi_data(url)
if oi_data:
data = oi_data.get(‘data’)
if data:
for item in data:
expiry_date = item.get(‘expiryDate’)
strike_price = item.get(‘strikePrice’)
ce_open_interest = item[‘CE’].get(‘openInterest’)
pe_open_interest = item[‘PE’].get(‘openInterest’)
print(f"Symbol: {symbol}, Expiry Date: {expiry_date}, Strike Price: {strike_price}, CE OI: {ce_open_interest}, PE OI: {pe_open_interest}“)
else:
print(f"No data found for symbol: {symbol}”)
else:
print(f"Failed to fetch data for symbol: {symbol}")
Store OI data for Bank Nifty and Nifty
store_oi_data(url_nf, ‘NIFTY’)
store_oi_data(url_bnf, ‘BANKNIFTY’)