Learn Algo Trading with Python | Codes | Youtube Series

Hello @Tradehull_Imran

I am trying to add Manual sell order using the code
sell_price = round((cc_1[‘close’]*2.0),1)
sell_orderid = tsl.order_placement(stock_name,‘NSE’, 2, 0, sell_price, ‘LIMIT’, ‘SELL’, ‘MIS’)

although it gets executed but the sell price is below buy price.
please help in this regard
Thanks

@Vijen_Singh @CapTn_Mohit @Manish_Goel @rejithkoroth @ddeogharkar @pratik_patil2 @Aijaz_Ahmad @Priyesh_Sharma @Kalpeshh_Patel
@Kishore007

If any issues in historical data, see below solutions

  1. Do check if you have subscribed to Data api and its not expired.

  2. It may be a version mismatch, we have to use now dhnahq 2.0.0 and Dhan_Tradehull_V2
    send below command to CMD

    
    pip uninstall dhanhq
    
    pip install dhanhq==2.0.0
    
    pip show dhanhq
    
    

    the output for pip show dhnahq shall be similar to
    Name: dhanhq
    Version: 2.0.0 # Double check if 2.0.0 is also showing on your laptop.
    Summary: The official Python client for communicating with the DhanHQ API
    Home-page: https://dhanhq.co/
    Author: Dhan
    Author-email: dhan-oss@dhan.co
    License: MIT LICENSE
    Location: c:\users\imran\appdata\local\programs\python\python38\lib\site-packages
    Requires: pandas, pyOpenSSL, requests, websockets
    Required-by:

  3. Make sure you are using Dhan_Tradehull_V2, the older versions will Dhan_Tradehull.py will be deprecated in future.
    Reference video for Dhan_Tradehull_V2 : https://www.youtube.com/watch?v=HLiEpNZSD80

  4. We can call historical data only once per second, so use sleep(0.7) after calling chart data

     chart_1          = tsl.get_historical_data(tradingsymbol = stock_name,exchange = 'NSE',timeframe="1")
     time.sleep(0.7)		
    
  5. See if you are using only supported timeframes
    Learn Algo Trading with Python | Codes | Youtube Series - #652 by Tradehull_Imran

  6. If still not solved after above solution, Send me main and support files
    a . Do send me main code file and Dhan_Tradehull_V2.py that you are using, on forum
    Do format code correctly see : Learn Algo Trading with Python | Codes | Youtube Series - #368 by Tradehull_Imran

    b. Also send the output of the command on CMD pip show dhanhq

@Vijen_Singh @CapTn_Mohit @Manish_Goel @rejithkoroth @ddeogharkar @pratik_patil2 @Aijaz_Ahmad @Priyesh_Sharma @Kalpeshh_Patel
@Kishore007

Also update me if these solutions worked,

Hi @Priyesh_Sharma

I will need more context to understand the issue you are facing, but on high level guess.

Lets say the cc_1[‘close’] is Rs 100

so using sell_price calculation

sell_price = round((cc_1[‘close’]*2.0),1)

the sell price value will become 200,

That is 200 RS SL limit order for 100 Rs Script.

So you can check on these lines,
also is you limit order is getting executed at market rate ?

Hi @rahulcse56

take reference of below code

            timeframe = str(timeframe)+"Min"
            logic = {'open':'first','high':'max','low':'min','close':'last','volume':'sum'}
            df = df.set_index('date')
            df = df.resample(timeframe, origin="start").agg(logic)
            # df = df.resample('W-FRI', origin= "start").agg(logic)
            df = df[df.isna().any(axis=1) == False]

Hello @Tradehull_Imran

I placed SL order and Limit sell order

sl_price = round((cc_1[‘close’]*0.98),1)
qty = int(per_trade_margin/cc_1[‘close’])
sell_price = round((cc_1[‘close’]*2.05),1)

sl_orderid = tsl.order_placement(stock_name,‘NSE’, qty, 0, sl_price, ‘STOPMARKET’, ‘SELL’, ‘MIS’)
sell_orderid = tsl.order_placement(stock_name,‘NSE’, qty, 0, sell_price, ‘LIMIT’, ‘SELL’, ‘MIS’)

SL order gets executed but Limit Sell order doesnt, I want to place +2% Sell Order above buy price…

Unable to plce NFO orders

buy_entry_orderid = tsl.order_placement('NIFTY 14 NOV 24000 PUT','NFO', 25, 0, 0, 'MARKET', 'BUY', 'MIS')
order_status  = tsl.get_order_status(orderid=buy_entry_orderid)
if order_status == "TRADED":
	print("I have double checked Order Completed")
	
order_price   = tsl.get_executed_price(orderid=buy_entry_orderid)
sl_price      = round((order_price*0.98),1)
sl_orderid = tsl.order_placement('NIFTY 14 NOV 24000 PUT','NFO', 25, 0, sl_price, 'STOPMARKET', 'SELL', 'MIS')
order_status  = tsl.get_order_status(orderid=sl_orderid)
if order_status == "TRADED":
	print("Stoploss Hit")

Output -
Traceback (most recent call last):
File “/home/mohan/Dhan-Alog-Trading/examples/Dhan_Tradehull_V2.py”, line 138, in order_placement
orderid = order[“data”][“orderId”]
~~~~~~~~~~~~~^^^^^^^^^^^
KeyError: ‘orderId’
‘62241112378127’

Hye Sir @Tradehull_Imran

Can we place Target orders instead of SL order, if so how?

Thanks for the solution… it worked fine now… but still i have a question that
“How to get day’s first candle from the last 6 days data ??” like today i am executing the algo… and i need it today’s first 2 min candle data.

@Tradehull_Imran
Hello Sir Still having issue with my code I have shared my code with you requesting you to check the same at your end.

Hi Sir, @Tradehull_Imran

Now the Algo is working with the following Erros, but the order has been placed.
Microsoft Windows [Version 10.0.22631.4391]
(c) Microsoft Corporation. All rights reserved.

C:\Users\Rejith Koroth\Desktop\REJITH KOROTH\DHAN_APP\DHAN ALGO\8.Session8\8. Session8- 2nd Live Algo_2\2nd live Algo>py “Multi timeframe Algo.py”
-----Logged into Dhan-----
reading existing file all_instrument 2024-11-12.csv
Got the instrument file
Traceback (most recent call last):
File “C:\Users\Rejith Koroth\Desktop\REJITH KOROTH\DHAN_APP\DHAN ALGO\8.Session8\8. Session8- 2nd Live Algo_2\2nd live Algo\Dhan_Tradehull_V2.py”, line 178, in get_live_pnl
closePrice = ltp_data[underlying]
KeyError: ‘NIFTY 14 NOV 24050 CALL’
MOTHERSON
OFSS
OFSS is in downtrend, Sell this script
MANAPPURAM
MANAPPURAM is in downtrend, Sell this script
BSOFT
CHAMBLFERT
DIXON
NATIONALUM
DLF
IDEA
ADANIPORTS
ADANIPORTS is in downtrend, Sell this script
SAIL
HINDCOPPER
HINDCOPPER is in downtrend, Sell this script
INDIGO
RECLTD
PNB
HINDALCO
RBLBANK
GNFC
ALKEM
CONCOR
PFC
GODREJPROP
MARUTI
ADANIENT
ONGC
CANBK
OBEROIRLTY
BANDHANBNK
SBIN
HINDPETRO
CANFINHOME
TATAMOTORS
LALPATHLAB
MCX
TATACHEM
BHARTIARTL
INDIAMART
LUPIN
INDUSTOWER
VEDL
SHRIRAMFIN
POLYCAB
WIPRO
UBL
SRF
BHARATFORG
GRASIM
IEX
BATAINDIA
AARTIIND
TATASTEEL
UPL
HDFCBANK
LTF
TVSMOTOR
GMRINFRA
IOC
ABCAPITAL
ACC
IDFCFIRSTB
ABFRL
ZYDUSLIFE
GLENMARK
TATAPOWER
PEL
IDFC
single positional indexer is out-of-bounds
Traceback (most recent call last):
File “C:\Users\Rejith Koroth\Desktop\REJITH KOROTH\DHAN_APP\DHAN ALGO\8.Session8\8. Session8- 2nd Live Algo_2\2nd live Algo\Dhan_Tradehull_V2.py”, line 244, in get_historical_data
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’]
File “C:\Users\Rejith Koroth\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\indexing.py”, line 1103, in getitem
return self._getitem_axis(maybe_callable, axis=axis)
File “C:\Users\Rejith Koroth\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\indexing.py”, line 1656, in _getitem_axis
self._validate_integer(key, axis)
File “C:\Users\Rejith Koroth\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\indexing.py”, line 1589, in _validate_integer
raise IndexError(“single positional indexer is out-of-bounds”)
IndexError: single positional indexer is out-of-bounds
Traceback (most recent call last):
File “Multi timeframe Algo.py”, line 57, in
chart_1[‘rsi’] = talib.RSI(chart_1[‘close’], timeperiod=14) #pandas
TypeError: ‘NoneType’ object is not subscriptable

C:\Users\Rejith Koroth\Desktop\REJITH KOROTH\DHAN_APP\DHAN ALGO\8.Session8\8. Session8- 2nd Live Algo_2\2nd live Algo>

C:\Users\Rejith Koroth\Desktop\REJITH KOROTH\DHAN_APP\DHAN ALGO\8.Session8\8. Session8- 2nd Live Algo_2\2nd live Algo>


<`# TA-Lib

Notion – The all-in-one workspace for your notes, tasks, wikis, and databases.

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

client_code = “1104068813”
token_id = “eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJkaGFuIiwicGFydG5lcklkIjoiIiwiZXhwIjoxNzMzODkxMTg1LCJ0b2tlbkNvbnN1bWVyVHlwZSI6IlNFTEYiLCJ3ZWJob29rVXJsIjoiIiwiZGhhbkNsaWVudElkIjoiMTEwNDA2ODgxMyJ9.ng5EkX1O_ZLx1CMvMyvUCpA6PFos9jKb90Nd8ZK99_YBhOCk2gnJn18CcLh8FoIswozr5K9oE2uSOoFMRr”

tsl = Tradehull(client_code,token_id)

available_balance = tsl.get_balance()
leveraged_margin = available_balance5
max_trades = 3
per_trade_margin = (leveraged_margin/max_trades)
max_loss = (available_balance
1)/100*-1

watchlist = [‘MOTHERSON’, ‘OFSS’, ‘MANAPPURAM’, ‘BSOFT’, ‘CHAMBLFERT’, ‘DIXON’, ‘NATIONALUM’, ‘DLF’, ‘IDEA’, ‘ADANIPORTS’, ‘SAIL’, ‘HINDCOPPER’, ‘INDIGO’, ‘RECLTD’, ‘PNB’, ‘HINDALCO’, ‘RBLBANK’, ‘GNFC’, ‘ALKEM’, ‘CONCOR’, ‘PFC’, ‘GODREJPROP’, ‘MARUTI’, ‘ADANIENT’, ‘ONGC’, ‘CANBK’, ‘OBEROIRLTY’, ‘BANDHANBNK’, ‘SBIN’, ‘HINDPETRO’, ‘CANFINHOME’, ‘TATAMOTORS’, ‘LALPATHLAB’, ‘MCX’, ‘TATACHEM’, ‘BHARTIARTL’, ‘INDIAMART’, ‘LUPIN’, ‘INDUSTOWER’, ‘VEDL’, ‘SHRIRAMFIN’, ‘POLYCAB’, ‘WIPRO’, ‘UBL’, ‘SRF’, ‘BHARATFORG’, ‘GRASIM’, ‘IEX’, ‘BATAINDIA’, ‘AARTIIND’, ‘TATASTEEL’, ‘UPL’, ‘HDFCBANK’, ‘LTF’, ‘TVSMOTOR’, ‘GMRINFRA’, ‘IOC’, ‘ABCAPITAL’, ‘ACC’, ‘IDFCFIRSTB’, ‘ABFRL’, ‘ZYDUSLIFE’, ‘GLENMARK’, ‘TATAPOWER’, ‘PEL’, ‘IDFC’, ‘LAURUSLABS’, ‘BANKBARODA’, ‘KOTAKBANK’, ‘CUB’, ‘GAIL’, ‘DABUR’, ‘TECHM’, ‘CHOLAFIN’, ‘BEL’, ‘SYNGENE’, ‘FEDERALBNK’, ‘NAVINFLUOR’, ‘AXISBANK’, ‘LT’, ‘ICICIGI’, ‘EXIDEIND’, ‘TATACOMM’, ‘RELIANCE’, ‘ICICIPRULI’, ‘IPCALAB’, ‘AUBANK’, ‘INDIACEM’, ‘GRANULES’, ‘HDFCAMC’, ‘COFORGE’, ‘LICHSGFIN’, ‘BAJAJFINSV’, ‘INFY’, ‘BRITANNIA’, ‘M&MFIN’, ‘BAJFINANCE’, ‘PIIND’, ‘DEEPAKNTR’, ‘SHREECEM’, ‘INDUSINDBK’, ‘DRREDDY’, ‘TCS’, ‘BPCL’, ‘PETRONET’, ‘NAUKRI’, ‘JSWSTEEL’, ‘MUTHOOTFIN’, ‘CUMMINSIND’, ‘CROMPTON’, ‘M&M’, ‘GODREJCP’, ‘IGL’, ‘BAJAJ-AUTO’, ‘HEROMOTOCO’, ‘AMBUJACEM’, ‘BIOCON’, ‘ULTRACEMCO’, ‘VOLTAS’, ‘BALRAMCHIN’, ‘SUNPHARMA’, ‘ASIANPAINT’, ‘COALINDIA’, ‘SUNTV’, ‘EICHERMOT’, ‘ESCORTS’, ‘HAL’, ‘ASTRAL’, ‘NMDC’, ‘ICICIBANK’, ‘TORNTPHARM’, ‘JUBLFOOD’, ‘METROPOLIS’, ‘RAMCOCEM’, ‘INDHOTEL’, ‘HINDUNILVR’, ‘TRENT’, ‘TITAN’, ‘JKCEMENT’, ‘ASHOKLEY’, ‘SBICARD’, ‘BERGEPAINT’, ‘JINDALSTEL’, ‘MFSL’, ‘BHEL’, ‘NESTLEIND’, ‘HDFCLIFE’, ‘COROMANDEL’, ‘DIVISLAB’, ‘ITC’, ‘TATACONSUM’, ‘APOLLOTYRE’, ‘AUROPHARMA’, ‘HCLTECH’, ‘LTTS’, ‘BALKRISIND’, ‘DALBHARAT’, ‘APOLLOHOSP’, ‘ABBOTINDIA’, ‘ATUL’, ‘UNITDSPR’, ‘PVRINOX’, ‘SIEMENS’, ‘SBILIFE’, ‘IRCTC’, ‘GUJGASLTD’, ‘BOSCHLTD’, ‘NTPC’, ‘POWERGRID’, ‘MARICO’, ‘HAVELLS’, ‘MPHASIS’, ‘COLPAL’, ‘CIPLA’, ‘MGL’, ‘ABB’, ‘PIDILITIND’, ‘MRF’, ‘LTIM’, ‘PAGEIND’, ‘PERSISTENT’]
traded_wathclist =

while True:

live_pnl = tsl.get_live_pnl()
current_time = datetime.datetime.now().time()

if current_time < datetime.time(9, 30):
	print("wait for market to start", current_time)
	continue


if (current_time > datetime.time(15, 15)) or (live_pnl < max_loss):
	I_want_to_trade_no_more = tsl.kill_switch('ON')
	order_details = tsl.cancel_all_orders()
	print("Market is over, Bye Bye see you tomorrow", current_time)
	break



for stock_name in watchlist:
	time.sleep(0.7)
	print(stock_name)



	# Conditions that are on 1 minute timeframe
	# chart_1        = tsl.get_intraday_data(stock_name, 'NSE', 1)       # 1 minute chart   # this call has been updated to get_historical_data call, 
	chart_1          = tsl.get_historical_data(tradingsymbol = stock_name,exchange = 'NSE',timeframe="1")


	chart_1['rsi'] = talib.RSI(chart_1['close'], timeperiod=14) #pandas
	cc_1           = chart_1.iloc[-2]  #pandas  completed candle of 1 min timeframe
	uptrend        = cc_1['rsi'] > 50
	downtrend      = cc_1['rsi'] < 49


	# Conditions that are on 5 minute timeframe
	# chart_5        = tsl.get_intraday_data(stock_name, 'NSE', 5)       # 5 minute chart
	chart_5          = tsl.get_historical_data(tradingsymbol = stock_name,exchange = 'NSE',timeframe="5") # this call has been updated to get_historical_data call, 
	chart_5['upperband'], chart_5['middleband'], chart_5['lowerband'] = talib.BBANDS(chart_5['close'], timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)
	cc_5           = chart_5.iloc[-1]   # pandas
	ub_breakout    = cc_5['high'] > cc_5['upperband']
	lb_breakout    = cc_5['low'] < cc_5['lowerband']

	no_repeat_order = stock_name not in traded_wathclist
	max_order_limit = len(traded_wathclist) <= max_trades


	if uptrend and ub_breakout and no_repeat_order and max_order_limit:
		print(stock_name, "is in uptrend, Buy this script")

		sl_price          = round((cc_1['close']*0.98),1)
		qty               = int(per_trade_margin/cc_1['close'])

		buy_entry_orderid = tsl.order_placement(stock_name,'NSE', 1, 0, 0, 'MARKET', 'BUY', 'MIS')
		sl_orderid        = tsl.order_placement(stock_name,'NSE', 1, 0, sl_price, 'STOPMARKET', 'SELL', 'MIS')
		traded_wathclist.append(stock_name)

	if downtrend and lb_breakout and no_repeat_order and max_order_limit:
		print(stock_name, "is in downtrend, Sell this script")

		sl_price          = round((cc_1['close']*1.02),1)
		qty               = int(per_trade_margin/cc_1['close'])

		buy_entry_orderid = tsl.order_placement(stock_name,'NSE', 1, 0, 0, 'MARKET', 'SELL', 'MIS')
		sl_orderid        = tsl.order_placement(stock_name,'NSE', 1, 0, sl_price, 'STOPMARKET', 'BUY', 'MIS')
		traded_wathclist.append(stock_name)

`

1 Like

@Tradehull_Imran
My issue is solved now.

  1. Check your Index name
chart= tsl.get_intraday_data(Stock_name,'NSE',15)
  1. Create new token and run code

These steps should fix the issue

2 Likes

df.iloc[0] == First candle

Hi @Tradehull_Imran ,

I have upgraded the dhan to 2.0, and ran the script, now the script runs fine for few mins and then it starts giving below error

are you facing the same issue?

can you please look into it.

Thanks,
Devendra

I too am getting the same error, script worked fine for few minutes and the got the same error.

Hi @Tradehull_Imran, @Hardik

Created a most basic script and I am getting error:

from dhanhq import dhanhq
import pdb


client_code = "1104227243"
token_id = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJkaGFuIiwicGFydG5lcklkIjoiIiwiZXhwIjoxNzMzNDA3Mzk2LCJ0b2tlbkNvbnN1bWVyVHlwZSI6IlNFTEYiLCJ3ZWJob29rVXJsIjoiIiwiZGhhbkNsaWVudElkIjoiMTEwNDIyNzI0MyJ9.A9sQHRh8v1giGGNYahiAZaNQrklQAc3XN96OPo0AgEqif319x6xzs1bM3Rg-AXoyXdV1o81e47RIKDBdk1eqjw"
dhan = dhanhq("client_id","access_token")


a = dhan.historical_daily_data(security_id = "1333",exchange_segment = 'NSE_EQ',instrument_type ='EQUITY', from_date = '2024-11-05',to_date = '2024-11-11')
print(a)

Error:

py Test.py
{'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.'}}

Created new token but still the same problem. Please help.

Hi, sir…

My Algo is working fine with different indicators and also placing the orders, but when I try to write Algo for Super trend it is showing Errors, I think , I made some mistake while coding super trend indicator.

Please check below code and guide me, sir…

# Conditions that are on 5 minute timeframe
		chart_5        = tsl.get_intraday_data(stock_name, 'NSE', 5)       # 5 minute chart
		chart_5          = tsl.get_historical_data(tradingsymbol = stock_name,exchange = 'NSE',timeframe="5") # this call has been updated to get_historical_data call, 

		chart_5 ['supertrend'] 	= ta.supertrend(chart_5['high'], chart_5['low'], chart_5['close'],7,3)
		chart_5 	= pd.concat([chart_5, supertrend], axis=1, join='inner')
		cc_5 		= chart_1.iloc[-1]

		ub_breakout    = cc_5['close'] > cc_5['supertrend']
		lb_breakout    = cc_5['close'] < cc_5['supertrend']

Code to apply ADX indicator, VWAP indicator and Stoch rsi indicator @Tradehull_Imran

1 Like

tsl = Tradehull(client_code,token_id)

Add the above code , after the access token

If it didn’t work then, I think access token is

expired .

Hi Guy,
I’m stuck at the same place.
Here is my code:

ohlc_data = dhan.intraday_minute_data( security_id=“35426”, exchange_segment=dhan.NSE_FNO, instrument_type=‘FUTIDX’, from_date=1731394800, to_date=1731420520, interval=5 )
I’m getting the following 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.’}}