Option chain expiry sensex historical data in excel

@Tradehull_Imran

from Dhan_Tradehull import Tradehull
import datetime
import pdb
import os



client_code = "000000 "
token_id    = "000000"
tsl         = Tradehull(client_code, token_id)

index_name = 'SENSEX'

no_strikes_to_replay = 10

expiry_date = "29 APR"

start_time ='2025-04-29 09:15:00+05:30'



today_date = datetime.datetime.now().date()

index_data = tsl.get_historical_data(tradingsymbol=index_name, exchange='INDEX', timeframe="1")

ATM_time_data = index_data[index_data['timestamp']==start_time]

if not ATM_time_data.empty:
    ATM_close = ATM_time_data.iloc[-1]['close']

step = tsl.index_step_dict[index_name]

ATM_Strike = round(ATM_close/step)*step

all_strikes = [ATM_Strike+(step*i) for i in range(1,no_strikes_to_replay+1)] + [ATM_Strike-(step*i) for i in range(1,no_strikes_to_replay+1)] + [ATM_Strike]

call_and_put_Strikes = [f"{index_name} {expiry_date} {strike} CALL" for strike in all_strikes] + [f"{index_name} {expiry_date} {strike} PUT" for strike in all_strikes]


file_path = f'data/{index_name}/{today_date}/'

directory = os.path.dirname(file_path)

if not os.path.exists(directory):
    os.makedirs(directory)

for strike in call_and_put_Strikes:
    option_df = tsl.get_historical_data(tradingsymbol=strike, exchange='NFO', timeframe="1")
    option_df.to_csv(f'data/{index_name}/{today_date}/{strike}.csv',index=False)





ERROR

.exe "c:/Dhan Option Chain/1. Download_Historical_data_SENSEX.pyCodebase Version 3
-----Logged into Dhan-----
reading existing file all_instrument 2025-04-29.csv
Got the instrument file
instrument_df Unnamed: 0 SEM_EXM_EXCH_ID … SEM_SERIES SM_SYMBOL_NAME
0 0 BSE … NaN USDIR
1 1 BSE … NaN GBPIR
2 2 BSE … NaN EURIR
3 3 BSE … NaN JPYIR
4 4 BSE … NaN EURUD
… … … … … …
177151 177151 NSE … 1 NATURALGS
177152 177152 NSE … 1 CRUDEOL
177153 177153 NSE … 1 CRUDEOL
177154 177154 NSE … 1 CRUDEOL
.exe "c:/Dhan Option Chain/1. Download_Historical_data_SENSEX.pyCodebase Version 3
-----Logged into Dhan-----
reading existing file all_instrument 2025-04-29.csv
Got the instrument file
instrument_df Unnamed: 0 SEM_EXM_EXCH_ID … SEM_SERIES SM_SYMBOL_NAME
0 0 BSE … NaN USDIR
1 1 BSE … NaN GBPIR
2 2 BSE … NaN EURIR
3 3 BSE … NaN JPYIR
4 4 BSE … NaN EURUD
… … … … … …
177151 177151 NSE … 1 NATURALGS
177152 177152 NSE … 1 CRUDEOL
177153 177153 NSE … 1 CRUDEOL
177154 177154 NSE … 1 CRUDEOL
.exe "c:/Dhan Option Chain/1. Download_Historical_data_SENSEX.pyCodebase Version 3
-----Logged into Dhan-----
reading existing file all_instrument 2025-04-29.csv
Got the instrument file
instrument_df Unnamed: 0 SEM_EXM_EXCH_ID … SEM_SERIES SM_SYMBOL_NAME
0 0 BSE … NaN USDIR
1 1 BSE … NaN GBPIR
2 2 BSE … NaN EURIR
3 3 BSE … NaN JPYIR
4 4 BSE … NaN EURUD
… … … … … …
177151 177151 NSE … 1 NATURALGS
177152 177152 NSE … 1 CRUDEOL
177153 177153 NSE … 1 CRUDEOL
177154 177154 NSE … 1 CRUDEOL
.exe "c:/Dhan Option Chain/1. Download_Historical_data_SENSEX.pyCodebase Version 3
-----Logged into Dhan-----
reading existing file all_instrument 2025-04-29.csv
Got the instrument file
instrument_df Unnamed: 0 SEM_EXM_EXCH_ID … SEM_SERIES SM_SYMBOL_NAME
0 0 BSE … NaN USDIR
1 1 BSE … NaN GBPIR
2 2 BSE … NaN EURIR
3 3 BSE … NaN JPYIR
4 4 BSE … NaN EURUD
… … … … … …
177151 177151 NSE … 1 NATURALGS
177152 177152 NSE … 1 CRUDEOL
177153 177153 NSE … 1 CRUDEOL
177154 177154 NSE … 1 CRUDEOL
reading existing file all_instrument 2025-04-29.csv
Got the instrument file
instrument_df Unnamed: 0 SEM_EXM_EXCH_ID … SEM_SERIES SM_SYMBOL_s x 17 columns]
NAME
0 0 BSE … NaN USDIR
1 1 BSE … NaN GBPIR
2 2 BSE … NaN EURIR
3 3 BSE … NaN JPYIR
4 4 BSE … NaN EURUD
… … … … … …
177151 177151 NSE … 1 NATURALGS
177152 177152 NSE … 1 CRUDEOL
177153 177153 NSE … 1 CRUDEOL
177154 177154 NSE … 1 CRUDEOL
177155 177155 NSE … 1 CRUDEOL

177155 177155 NSE … 1 CRUDEOLrom_date 2024-04-29

[177156 rows x 17 columns]
from_date 2024-04-29
instrument_df Unnamed: 0 SEM_EXM_EXCH_ID … SEM_SERIES 1 BSE … NaN GBPISM_SYMBOL_NAME
0 0 BSE … NaN USDIR

1 1 BSE … NaN GBPIR 4 BSE … NaN EURU

2 2 BSE … NaN EURI
[177156 rows x 17 columns]
from_date 2024-04-29
instrument_df Unnamed: 0 SEM_EXM_EXCH_ID … SEM_SERIES SM_SYMBOL_NAME
0 0 BSE … NaN USDINR
1 1 BSE … NaN GBPINR
2 2 BSE … NaN EURINR
3 3 BSE … NaN JPYINR
4 4 BSE … NaN EURUSD
… … … … … …
177151 177151 NSE … 1 NATURALGAS
177152 177152 NSE … 1 CRUDEOIL
177153 177153 NSE … 1 CRUDEOIL
177154 177154 NSE … 1 CRUDEOIL
177155 177155 NSE … 1 CRUDEOIL

[177156 rows x 17 columns]
from_date 2024-04-29
Exception in Getting OHLC data as Check the Tradingsymbol or Exchange
Traceback (most recent call last):
File “c:/Dhan Option Chain/1. Download_Historical_data_SENSEX.py”, line 49, in
option_df.to_csv(f’data/{index_name}/{today_date}/{strike}.csv’,index=False)
AttributeError: ‘NoneType’ object has no attribute ‘to_csv’
PS C:\Users\LENOVO>

Folder create but empty

Same problem for other index also

Hi @HEMANT_BAHIRAM ,

The code seems to be working fine. Do re check by placing pdb once.

Let me know if you face issue.

1 Like
rom Dhan_Tradehull import Tradehull
import datetime
import pdb
import time
import datetime 
import traceback
from Dhan_Tradehull import Tradehull
import pandas as pd
from pprint import pprint
from nsetools import Nse
import xlwings as xw
import os


client_code = "0000 "
token_id    = "0000"
tsl         = Tradehull(client_code,token_id)


data = tsl.get_historical_data(tradingsymbol='SENSEX', exchange='INDEX', timeframe="1")

pdb.set_trace()

# index_name = 'SENSEX'

# no_strikes_to_replay = 10

# expiry_date = "29 APR"

# start_time ='2025-04-29 09:15:00+05:30'

# today_date = datetime.datetime.now().date()

# index_data = tsl.get_historical_data(tradingsymbol=index_name, exchange='INDEX', timeframe="1")

# ATM_time_data = index_data[index_data['timestamp']==start_time]

# if not ATM_time_data.empty:
#     ATM_close = ATM_time_data.iloc[-1]['close']

# step = tsl.index_step_dict[index_name]

# ATM_Strike = round(ATM_close/step)*step

# all_strikes = [ATM_Strike+(step*i) for i in range(1,no_strikes_to_replay+1)] + [ATM_Strike-(step*i) for i in range(1,no_strikes_to_replay+1)] + [ATM_Strike]

# call_and_put_Strikes = [f"{index_name} {expiry_date} {strike} CALL" for strike in all_strikes] + [f"{index_name} {expiry_date} {strike} PUT" for strike in all_strikes]


# file_path = f'data/{index_name}/{today_date}/'

# directory = os.path.dirname(file_path)

# if not os.path.exists(directory):
#     os.makedirs(directory)

# for strike in call_and_put_Strikes:
#     option_df = tsl.get_historical_data(tradingsymbol=strike, exchange='NFO', timeframe="1")
#     option_df.to_csv(f'data/{index_name}/{today_date}/{strike}.csv',index=False)

Still same problem

PS C:\Dhan Option Chain> & C:/Users/LENOVO/AppData/Local/Programs/Python/Python38/python.exe “c:/Dhan Option Chain/1. Download_Historical_data.py”
Codebase Version 3
-----Logged into Dhan-----
reading existing file all_instrument 2025-04-30.csv
Got the instrument file
instrument_df Unnamed: 0 SEM_EXM_EXCH_ID … SEM_SERIES SM_SYMBOL_NAME
0 0 BSE … NaN USDINR
1 1 BSE … NaN GBPINR
2 2 BSE … NaN EURINR
3 3 BSE … NaN JPYINR
4 4 BSE … NaN EURUSD
… … … … … …
177917 177917 NSE … 1 NATURALGAS
177918 177918 NSE … 1 CRUDEOIL
177919 177919 NSE … 1 CRUDEOIL
177920 177920 NSE … 1 CRUDEOIL
177921 177921 NSE … 1 CRUDEOIL

[177922 rows x 17 columns]
from_date 2024-04-30
Exception in Getting OHLC data as {‘status’: ‘failure’, ‘remarks’: {‘error_code’: ‘DH-901’, ‘error_type’: ‘Invalid_Authentication’, ‘error_message’: ‘Client ID or user generated access token is invalid or expired.’}, ‘data’: {‘errorType’: ‘Invalid_Authentication’, ‘errorCode’: ‘DH-901’,
‘errorMessage’: ‘Client ID or user generated access token is invalid or
expired.’}}
–Return–
[0] > c:\dhan option chain\1. download_historical_data.py(22)()->None
→ pdb.set_trace()
(Pdb++)

even i try below mention

data = tsl.get_historical_data(tradingsymbol='NIFTY', exchange='INDEX', timeframe="1")

pdb.set_trace()

still output

“c:/dhan option chain/1. download_historical_data.py”
*** SyntaxError: invalid syntax
(Pdb++) data = tsl.get_historical_data(tradingsymbol=‘NIFTY’, exchange=‘INDEX’, timeframe=“1”)
instrument_df Unnamed: 0 SEM_EXM_EXCH_ID … SEM_SERIES SM_SYMBOL_NAME
0 0 BSE … NaN USDINR
1 1 BSE … NaN GBPINR
2 2 BSE … NaN EURINR
3 3 BSE … NaN JPYINR
4 4 BSE … NaN EURUSD
… … … … … …
177917 177917 NSE … 1 NATURALGAS
177918 177918 NSE … 1 CRUDEOIL
177919 177919 NSE … 1 CRUDEOIL
177920 177920 NSE … 1 CRUDEOIL
177921 177921 NSE … 1 CRUDEOIL

[177922 rows x 17 columns]
from_date 2024-04-30
Exception in Getting OHLC data as {‘status’: ‘failure’, ‘remarks’: {‘error_code’: ‘DH-901’, ‘error_type’: ‘Invalid_Authentication’, ‘error_message’: ‘Client ID or user generated access token is invalid or expired.’}, ‘data’:
{‘errorType’: ‘Invalid_Authentication’, ‘errorCode’: ‘DH-901’, ‘errorMessage’: ‘Client ID or user generated access token is invalid or expired.’}}
(Pdb++)

kindly provide update data ( code or database)

actually i wan to run Option_Chain_Replay ( for expiry option greeks)

Hi @HEMANT_BAHIRAM ,

‘error_message’: ‘Client ID or user generated access token is invalid or expired.

Itseems the access token may be expired due to which you may be facing this issue.

Follow below steps to Subscribe for Data API:

  1. Go to Profile Section
  2. Select “Dhan HQ Trading API”
  3. Switch to Data API tab
  4. Click Subscribe
  5. Revoke the access token and try
    Once you have active subscription you will be able to fetch historical and live data.

API Subscribe on 23 April 25 ( Status shown Active )
even reinstall and update python but still same issue to get option data or ltp

import pdb
import time
import datetime  # Single import for datetime
import traceback
from Dhan_Tradehull import Tradehull
import pandas as pd
from pprint import pprint
from nsetools import Nse
# Excel & Visualization
import xlwings as xw
import matplotlib.pyplot as plt  # type: ignore



client_code = "1103728918 "
token_id    = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJkaGFuIiwicGFydG5lcklkIjoiIiwiZXhwIjoxNzQ3OTg5MzUxLCJ0b2tlbkNvbnN1bWVyVHlwZSI6IlNFTEYiLCJ3ZWJob29rVXJsIjoiIiwiZGhhbkNsaWVudElkIjoiMTEwMzcyODkxOCJ9.XchV1EkFmrdSesCTQqpMoALVlB-TJkJz65-Wb_5bW8z_z67lQVcE5JU6sqE2J6n9koAPxlkf6pKpAPbX5dAPEA"
tsl_dhan    = Tradehull(client_code, token_id)


watchlist = ["HDFCBANK", "ICICIBANK", "NTPC" ]



for name in watchlist:
    chart = tsl_dhan.get_historical_data(tradingsymbol=name, exchange='NSE', timeframe="15") 
    print(name)
    print(chart)

chart = tsl_dhan.get_historical_data(tradingsymbol='NIFTY', exchange='INDEX', timeframe='15')
print(name)

kindly help to resolve the issue ( active API Details mention in above code)


Hi @HEMANT_BAHIRAM ,

Tagging @Dhan for the same