Learn Algo Trading with Python | Codes | Youtube Series

Hi
I have subscribed
And i just tried with new generated token but also shows error

C:\Algo Practice\Api Upgrade>py “New setup.py”
-----Logged into Dhan-----
reading existing file all_instrument 2024-11-17.csv
Got the instrument file
available_balance 261211.84
MOTHERSON
If using all scalar values, you must pass an index
Traceback (most recent call last):
File “C:\Algo Practice\Api Upgrade\Dhan_Tradehull_V2.py”, line 298, in get_intraday_data
df = pd.DataFrame(ohlc[‘data’])
File “C:\Users\kalpe\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\frame.py”, line 709, in init
mgr = dict_to_mgr(data, index, columns, dtype=dtype, copy=copy, typ=manager)
File “C:\Users\kalpe\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py”, line 481, in dict_to_mgr
return arrays_to_mgr(arrays, columns, index, dtype=dtype, typ=typ, consolidate=copy)
File “C:\Users\kalpe\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py”, line 115, in arrays_to_mgr
index = _extract_index(arrays)
File “C:\Users\kalpe\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py”, line 645, in _extract_index
raise ValueError(“If using all scalar values, you must pass an index”)
ValueError: If using all scalar values, you must pass an index
Traceback (most recent call last):
File “New setup.py”, line 54, in
chart_15[‘ma’] = talib.MA(chart_15(‘real’), timeperiod=20, matype=0)
TypeError: ‘DataFrame’ object is not callable

C:\Algo Practice\Api Upgrade>

Hi @Kalpeshh_Patel

  1. make changes in Dhan_Tradehull_V2.py, and send the error
	def get_intraday_data(self,tradingsymbol,exchange,timeframe):			
		try:
			available_frames = {
				2: '2T',    # 2 minutes
				3: '3T',    # 3 minutes
				5: '5T',    # 5 minutes
				10: '10T',   # 10 minutes
				15: '15T',   # 15 minutes
				30: '30T',   # 30 minutes
				60: '60T'    # 60 minutes
			}

			start_date =datetime.datetime.now().strftime('%Y-%m-%d')
			end_date = datetime.datetime.now().strftime('%Y-%m-%d')

			# script_exchange = {"NSE":self.Dhan.NSE, "NFO":self.Dhan.NSE_FNO, "BFO":self.Dhan.BSE_FNO, "CUR": self.Dhan.CUR, "BSE":self.Dhan.BSE, "MCX":self.Dhan.MCX}
			script_exchange = {"NSE":self.Dhan.NSE, "NFO":self.Dhan.FNO, "BFO":self.Dhan.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 tradingsymbol in index_exchange:
				exchange =index_exchange[tradingsymbol]	
			security_id = self.instrument_df[((self.instrument_df['SEM_TRADING_SYMBOL']==tradingsymbol)|(self.instrument_df['SEM_CUSTOM_SYMBOL']==tradingsymbol))&(self.instrument_df['SEM_EXM_EXCH_ID']==instrument_exchange[exchange])].iloc[-1]['SEM_SMST_SECURITY_ID']
			instrument_type = self.instrument_df[((self.instrument_df['SEM_TRADING_SYMBOL']==tradingsymbol)|(self.instrument_df['SEM_CUSTOM_SYMBOL']==tradingsymbol))&(self.instrument_df['SEM_EXM_EXCH_ID']==instrument_exchange[exchange])].iloc[-1]['SEM_INSTRUMENT_NAME']
			ohlc = self.Dhan.intraday_minute_data(str(security_id),exchange_segment,instrument_type,start_date,end_date,int(1))
			print(ohlc)    # this is the only line that you have to add




			if len(ohlc['data'])!=0:
				df = pd.DataFrame(ohlc['data'])
				if not df.empty:
					df['timestamp'] = df['timestamp'].apply(lambda x: self.convert_to_date_time(x))
					if timeframe==1:
						return df
					df = self.resample_timeframe(df,available_frames[timeframe])
					return df
				else:
					return df
			else:
				return None 
		except Exception as e:
			print(e)
			self.logger.exception(f"Exception in Getting OHLC data as {e}")
			traceback.print_exc()

  1. Also try using new function for histrical data
    data = tsl.get_historical_data(debug = “yes”, tradingsymbol = ‘ACC’ ,exchange = ‘NSE’ ,timeframe=“15”)

  2. Send me pip show dhanhq result

Hi
pip show dhanhq result attached

The given code replace with selected lines, right?

After trying new function

C:\Algo Practice\Api Upgrade>py “1. Easy way to get LTP.py”
File “1. Easy way to get LTP.py”, line 29
data = tsl.get_historical_data(debug = “yes”, tradingsymbol = ‘ACC’ ,exchange = ‘NSE’ ,timeframe=“15”)
^

I have changed the lines but result same

C:\Algo Practice\Api Upgrade>py “New setup.py”
-----Logged into Dhan-----
reading existing file all_instrument 2024-11-17.csv
Got the instrument file
available_balance 261211.84
MOTHERSON
{‘status’: ‘failure’, ‘remarks’: {‘error_code’: ‘DH-907’, ‘error_type’: ‘Data_Error’, ‘error_message’: ‘System is unable to fetch data due to incorrect parameters or no data present’}, ‘data’: {‘errorType’: ‘Data_Error’, ‘errorCode’: ‘DH-907’, ‘errorMessage’: ‘System is unable to fetch data due to incorrect parameters or no data present’}}
If using all scalar values, you must pass an index
Traceback (most recent call last):
File “C:\Algo Practice\Api Upgrade\Dhan_Tradehull_V2.py”, line 303, in get_intraday_data
df = pd.DataFrame(ohlc[‘data’])
File “C:\Users\kalpe\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\frame.py”, line 709, in init
mgr = dict_to_mgr(data, index, columns, dtype=dtype, copy=copy, typ=manager)
File “C:\Users\kalpe\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py”, line 481, in dict_to_mgr
return arrays_to_mgr(arrays, columns, index, dtype=dtype, typ=typ, consolidate=copy)
File “C:\Users\kalpe\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py”, line 115, in arrays_to_mgr
index = _extract_index(arrays)
File “C:\Users\kalpe\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py”, line 645, in _extract_index
raise ValueError(“If using all scalar values, you must pass an index”)
ValueError: If using all scalar values, you must pass an index
Traceback (most recent call last):
File “New setup.py”, line 54, in
chart_15[‘ma’] = talib.MA(chart_15(‘real’), timeperiod=20, matype=0)
TypeError: ‘DataFrame’ object is not callable

C:\Algo Practice\Api Upgrade>

Hi @Tradehull_Imran ,

You are right the issue is because of CRUDEOIL APR FUT
I have added the below change
chart_1 = tsl.get_historical_data(tradingsymbol = stock_name,exchange = ‘MCX’,timeframe=“5”)
time.sleep(0.7)

but still, the issue continues.

Thanks,
Devendra

Hi @Kalpeshh_Patel

The main error is

Do post your New setup.py and Dhan_Tradehull_V2.py

Sir do we need to subscribe data Api every month ?

Hi Imran Sir,

Getting below error while running the codebase script session 6.
D:\Algo\Sessions\6. Session6- 1st Live Algo\1st live Algo>py “Dhan_codebase usage.py”
-----Logged into Dhan-----
reading existing file all_instrument 2024-11-17.csv
Got the instrument file
MOTHERSON
intraday_minute_data() missing 2 required positional arguments: ‘from_date’ and ‘to_date’
Traceback (most recent call last):
File “D:\Algo\Sessions\6. Session6- 1st Live Algo\1st live Algo\Dhan_Tradehull.py”, line 253, in get_intraday_data
ohlc = self.Dhan.intraday_minute_data(str(security_id),exchangeSegment,instrument_type)
TypeError: intraday_minute_data() missing 2 required positional arguments: ‘from_date’ and ‘to_date’
Traceback (most recent call last):
File “Dhan_codebase usage.py”, line 28, in
chart[‘rsi’] = talib.RSI(chart[‘close’], timeperiod=14) #pandas
TypeError: ‘NoneType’ object is not subscriptable

Hi @Arun_Rawat

The codebase has been updated,
This update helps us to get LTP data and Solves much of the Historical data related issues

see : Learn Algo Trading with Python | Codes | Youtube Series - #631 by Tradehull_Imran

Most of Algo Traders using TradeHull facing errors, its because access token has expired, Generate new token and Algo will work

1 Like

hello @Tradehull_Imran,

my algo was working on Thursday, but today its not working and giving the below error… i have updated my access token as well. It seems that algo is not able to fetch intraday data. please help.

If using all scalar values, you must pass an index
Traceback (most recent call last):
File “C:\Python\Dhan API Python\New Series\1. Api Upgrade\1. Api Upgrade\Dhan_Tradehull_V2.py”, line 266, in get_historical_data
df = pd.DataFrame(ohlc[‘data’])


Hi @Tradehull_Imran

Algo worked on thursday, generated new API but still getting the error

Hi @Tradehull_Imran,

Till Thursday my code was working, but today I am getting this error:

{'status': 'failure', 'remarks': {'error_code': 'DH-905', 'error_type': 'Input_Exception', 'error_message': 'Missing required fields, bad values for parameters etc.'}, 'data': {'errorType': 'Input_Exception', 'errorCode': 'DH-905', 'errorMessage': 'Missing required fields, bad values for parameters etc.'}}
No intraday data available for JGCHEM
{'status': 'failure', 'remarks': {'error_code': 'DH-905', 'error_type': 'Input_Exception', 'error_message': 'Missing required fields, bad values for parameters etc.'}, 'data': {'errorType': 'Input_Exception', 'errorCode': 'DH-905', 'errorMessage': 'Missing required fields, bad values for parameters etc.'}}
No intraday data available for ANUP
{'status': 'failure', 'remarks': {'error_code': 'DH-905', 'error_type': 'Input_Exception', 'error_message': 'Missing required fields, bad values for parameters etc.'}, 'data': {'errorType': 'Input_Exception', 'errorCode': 'DH-905', 'errorMessage': 'Missing required fields, bad values for parameters etc.'}}
No intraday data available for MARKSANS

this is the code which I am using to get intraday data:

intraday_data = tsl.get_historical_data(tradingsymbol=stock_name, exchange='NSE', timeframe='5')

though this code works fine:

VolumeAverageDaily = tsl.get_historical_data(tradingsymbol=stock_name, exchange='NSE', timeframe='DAY')

output:
       open    high     low   close     volume   timestamp
0    141.20  141.70  135.65  137.85  2353799.0  2023-11-20
1    139.25  140.35  136.70  139.00  2039639.0  2023-11-21
2    140.00  143.00  137.85  139.65  2805017.0  2023-11-22
3    140.40  147.90  139.35  144.70  7513608.0  2023-11-23
4    145.00  145.65  141.00  141.85  2014210.0  2023-11-24
..      ...     ...     ...     ...        ...         ...
242  302.30  309.70  292.00  299.40  2370835.0  2024-11-08
243  296.80  298.25  284.40  288.60  2086964.0  2024-11-11
244  290.70  310.95  289.25  300.50  6810715.0  2024-11-12
245  302.00  318.00  298.30  305.70  7373040.0  2024-11-13
246  306.60  325.00  304.55  308.30  5876224.0  2024-11-14

Hi
@Tradehull_Imran

Here am sharing files
https://drive.google.com/drive/folders/1espgCTE4RmqrSVbwQ6u1P9y9AjYAgtb2?usp=sharing
Waitnig for solution

Thank you for your valuable support

Hi @Tradehull_Imran

Hope you are doing well

I have updated to Dhan_Tradehull_v2 and tried to pull ltp data but it is showing blank. Could you please check and guide me.

Hi @Kalpeshh_Patel

The code seems to be working fine, I will share updated files in a while.

@Tradehull_Imran sir I am getting below error

 C:\Users\Subhajit Panja\Documents\Algorithim_HQ> & "c:/Users/Subhajit Panja/Documents/Algorithim_HQ/.venv/Scripts/python.exe" "c:/Users/Subhajit Panja/Documents/Algorithim_HQ/Api Upgrade/0. How to use upgraded files.py"
-----Logged into Dhan-----
reading existing file all_instrument 2024-11-18.csv
Got the instrument file
NIFTY 23450.15
BANKNIFTY 50348.1
CRUDEOIL 5655
CRUDEOIL 16 DEC 5950 CALL 115.4
CRUDEOIL 16 DEC 5950 PUT 322
RELIANCE 1255.8
NIFTY 28 NOV 24000 CALL 46.05
NIFTY 28 NOV 24000 PUT 531.2
If using all scalar values, you must pass an index
Traceback (most recent call last):
  File "c:\Users\Subhajit Panja\Documents\Algorithim_HQ\Api Upgrade\Dhan_Tradehull_V2.py", line 259, in get_historical_data
    df = pd.DataFrame(ohlc['data'])
  File "C:\Users\Subhajit Panja\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\frame.py", line 709, in __init__
    mgr = dict_to_mgr(data, index, columns, dtype=dtype, copy=copy, typ=manager)
  File "C:\Users\Subhajit Panja\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py", line 481, in dict_to_mgr    
    return arrays_to_mgr(arrays, columns, index, dtype=dtype, typ=typ, consolidate=copy)
  File "C:\Users\Subhajit Panja\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py", line 115, in arrays_to_mgr  
    index = _extract_index(arrays)
  File "C:\Users\Subhajit Panja\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py", line 645, in _extract_index 
    raise ValueError("If using all scalar values, you must pass an index")
ValueError: If using all scalar values, you must pass an index
If using all scalar values, you must pass an index
Traceback (most recent call last):
  File "c:\Users\Subhajit Panja\Documents\Algorithim_HQ\Api Upgrade\Dhan_Tradehull_V2.py", line 259, in get_historical_data
    df = pd.DataFrame(ohlc['data'])
  File "C:\Users\Subhajit Panja\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\frame.py", line 709, in __init__
    mgr = dict_to_mgr(data, index, columns, dtype=dtype, copy=copy, typ=manager)
  File "C:\Users\Subhajit Panja\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py", line 481, in dict_to_mgr    
    return arrays_to_mgr(arrays, columns, index, dtype=dtype, typ=typ, consolidate=copy)
  File "C:\Users\Subhajit Panja\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py", line 115, in arrays_to_mgr  
    index = _extract_index(arrays)
  File "C:\Users\Subhajit Panja\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\internals\construction.py", line 645, in _extract_index 
    raise ValueError("If using all scalar values, you must pass an index")
ValueError: If using all scalar values, you must pass an index
Traceback (most recent call last):
  File "c:/Users/Subhajit Panja/Documents/Algorithim_HQ/Api Upgrade/0. How to use upgraded files.py", line 39, in <module>
    options_chart['ema_30'] = talib.EMA(options_chart['close'], timeperiod=30)
TypeError: 'NoneType' object is not subscriptable

here is my file below

# pip install --upgrade dhanhq

import pdb
import time
import datetime
import traceback
from Dhan_Tradehull_V2 import Tradehull
import pandas as pd
from pprint import pprint
import talib

# ---------------for dhan login ----------------
client_code = 
token_id =

tsl = Tradehull(client_code,token_id)

ltp_data = tsl.get_ltp_data(names = [
    'BANKNIFTY', 
    'NIFTY' ,
    'CRUDEOIL', 
    'RELIANCE', 
    'NIFTY 28 NOV 24000 CALL', 
    'NIFTY 28 NOV 24000 PUT', 
    'CRUDEOIL 16 DEC 5950 CALL', 
    'CRUDEOIL 16 DEC 5950 PUT'
])

for script_name,ltp in ltp_data.items():
    print(script_name, ltp)



data = tsl.get_historical_data(tradingsymbol = 'BANKNIFTY',exchange = 'INDEX',timeframe="DAY")
data = tsl.get_historical_data(tradingsymbol = 'ACC'     ,exchange = 'NSE'  ,timeframe="15")


options_chart = tsl.get_historical_data(tradingsymbol = 'NIFTY 28 NOV 24000 CALL'     ,exchange = 'NFO'  ,timeframe="15")
options_chart['ema_30'] = talib.EMA(options_chart['close'], timeperiod=30)

data = tsl.get_historical_data(tradingsymbol = 'CRUDEOIL DEC FUT' ,exchange = 'MCX'  ,timeframe="15")
data = tsl.get_historical_data(tradingsymbol = 'CRUDEOIL 16 DEC 5950 CALL'     ,exchange = 'MCX'  ,timeframe="15")

print (data)




ce_strike, pe_strike, strike = tsl.ATM_Strike_Selection(Underlying ='CRUDEOIL',Expiry ='16-12-2024')
ce_strike, pe_strike, ce_OTM_price, pe_OTM_price = tsl.OTM_Strike_Selection(Underlying ='CRUDEOIL',Expiry ='16-12-2024',OTM_count=5)
ce_strike, pe_strike, ce_ITM_price, pe_ITM_price = tsl.ITM_Strike_Selection(Underlying = 'CRUDEOIL',Expiry = '16-12-2024',ITM_count=1)



@Tradehull_Imran Sir I think problem is still same for me
excel file name still old date I have tried with other file also

Hi
Waiting for updated file

Thank you

@Tradehull_Imran sir
I just updated from below

excel file still old name

facing error as in get_intraday_data from traedehull libarray, i guess there is soma problem in tradehull libraray in from_date and to_dtae

@thakurmhn @Kalpeshh_Patel @Subhajitpanja @Jyothi_Chilukoti @Aijaz_Ahmad @Priyesh_Sharma @Arun_Rawat @Shravan_Kotagi

we have made some changes in Dhan_Tradehull_V2 related to debug mode and start date in historical data

  1. Download the updated Tradehull_Dhan_V2
    Dhan_Tradehull_V2.py - Google Drive

  2. In you folder delete existing Tradehull_Dhan_V2 and paste the recently downloaded Tradehull_Dhan_V2

  3. Run your code again. If any issues, share me the google drive link

3 Likes