Learn Algo Trading with Python | Codes | Youtube Series

Hi @DEBJYOTI_GHOSE ,

Do refer this thread-
https://private-poc.madefortrade.in/t/crude-oiloption/45154/7?u=tradehull_imran

didn’t find the code in version 1
@Tradehull_Imran

not get the line as you mention earlier comment in Tradehull version 2
@Tradehull_Imran


Getting only Future data in commodity.
Option data is not getting any way.
@Tradehull_Imran

C:\Users\WELCOME\Desktop\python\3. Session3 - Codebase\3. Session3 - Codebase\Dhan codebase>PY “Automatic Nifty Options ORB Trading Bot.py”
2025-11-11 10:46:56,235 - INFO - Instruments loaded.
2025-11-11 10:46:56,236 - INFO - Dhan connected.
2025-11-11 10:46:56,497 - INFO - EXPIRY → 11-11-2025
2025-11-11 10:46:56,497 - INFO - Trying 9:30–9:35 ORB…
2025-11-11 10:46:56,579 - WARNING - ORB data not available
2025-11-11 10:46:56,643 - ERROR - CRITICAL: Cannot get price from option chain: ‘underlying_price’

C:\Users\WELCOME\Desktop\python\3. Session3 - Codebase\3. Session3 - Codebase\Dhan codebase>

@Tradehull_Imran, I have been looking at the series (Master Algo Trading with Python) and following your videos, I have tried using the exact method you mentioned in the video regarding WebSocket however I am getting connection error HTTP 400 while running the WebSocket, also I have tried to join the community but I am not getting the email verification link to join the community hence raising the issue I am facing here. (Data API Subscribed, Access token refreshed & client id and access token replaced the code). I would really appreciate it if you could assist me in solving this issue.

Attached herewith are the screenshot for your reference !

Hi @DEBJYOTI_GHOSE ,

  • Scroll or search (Ctrl + F) for the below function:
def get_option_chain():

Hi @DEBJYOTI_GHOSE ,

Refer the below code-

strike,option_chain = tsl.get_option_chain("GOLD", "MCX",0,10)

Hi @gaming_with_rowdy ,

Can you share your query in detail?

Hey algo traders :waving_hand:t3:

We love the enthusiasm here, and can see your efforts into improving your trading strategies using different algo trading techniques.

To ensure quicker doubt resolution and encourage community learning, we at Upsurge and Dhan are coming together for a LIVE Q&A session with Imran Ali :bullseye:

This is your chance to ask Imran directly and get clear, easy answers to your doubts, along with an opportunity to learn from fellow algo traders!

We promise to answer each & every doubt in this free session :white_check_mark:

:spiral_calendar: Date: 13th November 2025
:three_o_clock: Time: 8:00 pm onwards
:right_arrow: Register here: Upsurge.club

Hope to see you all there!

@Tradehull_Imran, any luck on this issue ?

Hi @DEBJYOTI_GHOSE ,

You have implemeted the code changes in Dhan_Tradehull_V2.py file but importing Dhan_Tradehull.py. Make sure you use the updated codebase version and make necessary changes in that file.

1 Like

Hi @JKK62 ,

WebSocket is a old method we used to get data, Now we have upgraded to a easier method to fetch LTP using REST API calls

See this video : https://www.youtube.com/watch?v=HLiEpNZSD80

Hi @DEBJYOTI_GHOSE and @Tradehull_Imran use function get_option_chain from Dhan_Tradehull.py file and replace into the Dhan_Tradehull_V2.py then it should work

Below function is from Dhan_Tradehull.py file

	def get_option_chain(self, Underlying, exchange, expiry,num_strikes = 10):
		try:
			Underlying = Underlying.upper()
			exchange = exchange.upper()
			script_exchange = {"NSE":self.Dhan.NSE, "NFO":self.Dhan.FNO, "BFO":"BSE_FNO", "CUR": self.Dhan.CUR, "BSE":self.Dhan.BSE, "MCX":self.Dhan.MCX, "INDEX":self.Dhan.INDEX}
			instrument_exchange = {'NSE':"NSE",'BSE':"BSE",'NFO':'NSE','BFO':'BSE','MCX':'MCX','CUR':'NSE'}
			exchange_segment = script_exchange[exchange]
			index_exchange = {"NIFTY":'NSE',"BANKNIFTY":"NSE","FINNIFTY":"NSE","MIDCPNIFTY":"NSE","BANKEX":"BSE","SENSEX":"BSE"}
			
			if Underlying in index_exchange:
				exchange =index_exchange[Underlying]

			if Underlying in self.commodity_step_dict.keys():
				security_check = instrument_df[(instrument_df['SEM_EXM_EXCH_ID']=='MCX')&(instrument_df['SM_SYMBOL_NAME']==Underlying.upper())&(instrument_df['SEM_INSTRUMENT_NAME']=='FUTCOM')]                        
				if security_check.empty:
					raise Exception("Check the Tradingsymbol")
				security_id = security_check.sort_values(by='SEM_EXPIRY_DATE').iloc[0]['SEM_SMST_SECURITY_ID']
			else:                       
				security_check = instrument_df[((instrument_df['SEM_TRADING_SYMBOL']==Underlying)|(instrument_df['SEM_CUSTOM_SYMBOL']==Underlying))&(instrument_df['SEM_EXM_EXCH_ID']==instrument_exchange[exchange])]
				if security_check.empty:
					raise Exception("Check the Tradingsymbol")
				security_id = security_check.iloc[-1]['SEM_SMST_SECURITY_ID']

			if Underlying in index_exchange:
				expiry_exchange = 'INDEX'
			elif Underlying in self.commodity_step_dict.keys():
				exchange = "MCX"
				expiry_exchange = exchange
			else:
				# exchange = instrument_df[((instrument_df['SEM_TRADING_SYMBOL']==Underlying)|(instrument_df['SEM_CUSTOM_SYMBOL']==Underlying))].iloc[0]['SEM_EXM_EXCH_ID']
				exchange = "NSE"
				expiry_exchange = exchange

			expiry_list = self.get_expiry_list(Underlying=Underlying, exchange = expiry_exchange)

			if len(expiry_list)==0:
				print(f"Unable to find the correct Expiry for {Underlying}")
				return None
			if len(expiry_list)<expiry:
				Expiry_date = expiry_list[-1]
			else:
				Expiry_date = expiry_list[expiry]                       

			# time.sleep(3)
			response = self.Dhan.option_chain(under_security_id =int(security_id), under_exchange_segment = exchange_segment, expiry = Expiry_date)
			if response['status']=='success':
				oc = response['data']['data']
				oc_df = self.format_option_chain(oc)

				atm_price = self.get_ltp_data(Underlying)
				oc_df['Strike Price'] = pd.to_numeric(oc_df['Strike Price'], errors='coerce')
				# strike_step = self.stock_step_df[Underlying]
				if Underlying in self.index_step_dict:
					strike_step = self.index_step_dict[Underlying]
				elif Underlying in self.stock_step_df:
					strike_step = self.stock_step_df[Underlying]
				elif Underlying in self.commodity_step_dict:
					strike_step = self.commodity_step_dict[Underlying]
				else:
					raise Exception(f"No option chain data available for the {Underlying}")
				# atm_strike = oc_df.loc[(oc_df['Strike Price'] - atm_price[Underlying]).abs().idxmin(), 'Strike Price']
				atm_strike = round(atm_price[Underlying]/strike_step) * strike_step

				df = oc_df[(oc_df['Strike Price'] >= atm_strike - num_strikes * strike_step) & (oc_df['Strike Price'] <= atm_strike + num_strikes * strike_step)].sort_values(by='Strike Price').reset_index(drop=True)
				return atm_strike, df
			else:
				raise Exception(response)           
		except Exception as e:
			print(f"Getting Error at Option Chain as {e}")

go to Dhan_Tradehull_V2.py file and search for the def get_option_chain and replace with below code

	def get_option_chain(self, Underlying, exchange, expiry,num_strikes = 10):
		try:
			Underlying = Underlying.upper()
			exchange = exchange.upper()
			script_exchange = {"NSE":self.Dhan.NSE, "NFO":self.Dhan.FNO, "BFO":"BSE_FNO", "CUR": self.Dhan.CUR, "BSE":self.Dhan.BSE, "MCX":self.Dhan.MCX, "INDEX":self.Dhan.INDEX}
			instrument_exchange = {'NSE':"NSE",'BSE':"BSE",'NFO':'NSE','BFO':'BSE','MCX':'MCX','CUR':'NSE'}
			exchange_segment = script_exchange[exchange]
			index_exchange = {"NIFTY":'NSE',"BANKNIFTY":"NSE","FINNIFTY":"NSE","MIDCPNIFTY":"NSE","BANKEX":"BSE","SENSEX":"BSE"}
			
			if Underlying in index_exchange:
				exchange =index_exchange[Underlying]

			if Underlying in self.commodity_step_dict.keys():
				security_check = instrument_df[(instrument_df['SEM_EXM_EXCH_ID']=='MCX')&(instrument_df['SM_SYMBOL_NAME']==Underlying.upper())&(instrument_df['SEM_INSTRUMENT_NAME']=='FUTCOM')]                        
				if security_check.empty:
					raise Exception("Check the Tradingsymbol")
				security_id = security_check.sort_values(by='SEM_EXPIRY_DATE').iloc[0]['SEM_SMST_SECURITY_ID']
			else:                       
				security_check = instrument_df[((instrument_df['SEM_TRADING_SYMBOL']==Underlying)|(instrument_df['SEM_CUSTOM_SYMBOL']==Underlying))&(instrument_df['SEM_EXM_EXCH_ID']==instrument_exchange[exchange])]
				if security_check.empty:
					raise Exception("Check the Tradingsymbol")
				security_id = security_check.iloc[-1]['SEM_SMST_SECURITY_ID']

			if Underlying in index_exchange:
				expiry_exchange = 'INDEX'
			elif Underlying in self.commodity_step_dict.keys():
				exchange = "MCX"
				expiry_exchange = exchange
			else:
				# exchange = instrument_df[((instrument_df['SEM_TRADING_SYMBOL']==Underlying)|(instrument_df['SEM_CUSTOM_SYMBOL']==Underlying))].iloc[0]['SEM_EXM_EXCH_ID']
				exchange = "NSE"
				expiry_exchange = exchange

			expiry_list = self.get_expiry_list(Underlying=Underlying, exchange = expiry_exchange)

			if len(expiry_list)==0:
				print(f"Unable to find the correct Expiry for {Underlying}")
				return None
			if len(expiry_list)<expiry:
				Expiry_date = expiry_list[-1]
			else:
				Expiry_date = expiry_list[expiry]                       

			# time.sleep(3)
			response = self.Dhan.option_chain(under_security_id =int(security_id), under_exchange_segment = exchange_segment, expiry = Expiry_date)
			if response['status']=='success':
				oc = response['data']['data']
				oc_df = self.format_option_chain(oc)

				atm_price = self.get_ltp_data(Underlying)
				oc_df['Strike Price'] = pd.to_numeric(oc_df['Strike Price'], errors='coerce')
				# strike_step = self.stock_step_df[Underlying]
				if Underlying in self.index_step_dict:
					strike_step = self.index_step_dict[Underlying]
				elif Underlying in self.stock_step_df:
					strike_step = self.stock_step_df[Underlying]
				elif Underlying in self.commodity_step_dict:
					strike_step = self.commodity_step_dict[Underlying]
				else:
					raise Exception(f"No option chain data available for the {Underlying}")
				# atm_strike = oc_df.loc[(oc_df['Strike Price'] - atm_price[Underlying]).abs().idxmin(), 'Strike Price']
				atm_strike = round(atm_price[Underlying]/strike_step) * strike_step

				df = oc_df[(oc_df['Strike Price'] >= atm_strike - num_strikes * strike_step) & (oc_df['Strike Price'] <= atm_strike + num_strikes * strike_step)].sort_values(by='Strike Price').reset_index(drop=True)
				return atm_strike, df
			else:
				raise Exception(response)           
		except Exception as e:
			print(f"Getting Error at Option Chain as {e}")

It should work otherwise send the code which are you using.

upgrade Dhan-Tradehull v 3.0.6. But that code won’t be visible since it will download from backend.

Also remember, not using websocket anymore.

1 Like

Thank you sir. I got my mistake and code is run properly :folded_hands:

2 Likes

Watch Episode 3.1, in the update Dhan removed websocket and updated accordingly.

Exception for instrument name INDIA VIX as Check the Tradingsymbol
:warning: Error: {KeyError(‘INDIA VIX’)}

facing error for india vix ltp data