Learn Algo Trading with Python | Codes | Youtube Series

Hi @mobile2024 ,

Can you brief more about it. You can start coding referring the below playlist:

1 Like

Hi @Simardeep_Singh ,

Currently “DAY” timeframe is not supported by DHANHQ.
Adding @Hardik for the same.

1 Like

Hi @Siddh_Shah,

Yes, bracket order will be supported in upcoming codebase release.

2 Likes

@Tradehull_Imran Sir, thanks for your support.
Please check the below given Error logs…

I think the get_historical_data() use the DataAPI which has 10000 limit per day.

that is the reason I was requesting to extend this method to support list of scripts to fetch chart_data in multiple time frames.

Without this support we are encountering this limit error because of unnecessarily wasting the Data API call to fetch chart _data of 1 script in 1 API call.
Please look into this to extend the get_historical_data() to get_historical_data_mulitiple().
thanks for your support once again

2025-01-08 12:53:42,929 - INFO - Retrieving current state of TRADED_WATCHLIST and EXITED_WATCHLIST.

2025-01-08 12:53:42,929 - INFO - Update watchlist bull content: {‘TRADED_WATCHLIST’: {}, ‘EXITED_WATCHLIST’: set()}

2025-01-08 12:53:42,929 - INFO -
TRADED_WATCHLIST: {}

2025-01-08 12:53:42,929 - INFO -
EXITED_WATCHLIST: set()

2025-01-08 12:53:42,930 - INFO - Processing NEOGEN for trading conditions.

2025-01-08 12:53:42,930 - INFO - Processing NEOGEN for trading conditions.

2025-01-08 12:53:45,069 - ERROR - Exception in Getting OHLC data as {‘status’: ‘failure’, ‘remarks’: {‘error_code’: ‘DH-904’, ‘error_type’: ‘Rate_Limit’, ‘error_message’: ‘Too many requests on server from single user breaching rate limits. Try throttling API calls.’}, ‘data’: {‘errorType’: ‘Rate_Limit’, ‘errorCode’: ‘DH-904’, ‘errorMessage’: ‘Too many requests on server from single user breaching rate limits. Try throttling API calls.’}}
Traceback (most recent call last):
File “D:\Python_Project\Working Directory\NSE\Dhan_Tradehull_V26.py”, line 502, in get_historical_data
raise Exception(ohlc)
Exception: {‘status’: ‘failure’, ‘remarks’: {‘error_code’: ‘DH-904’, ‘error_type’: ‘Rate_Limit’, ‘error_message’: ‘Too many requests on server from single user breaching rate limits. Try throttling API calls.’}, ‘data’: {‘errorType’: ‘Rate_Limit’, ‘errorCode’: ‘DH-904’, ‘errorMessage’: ‘Too many requests on server from single user breaching rate limits. Try throttling API calls.’}}
2025-01-08 12:53:45,077 - INFO - @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@
NEOGEN :
None @@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

Hello @Tradehull_Imran

Day timeframe for current day or historically? If historically, then this is available for NSE & BSE Future instruments.

Hello Imran, thank you for the response. I am not able to implement the python code as i am not developer, I need a basic code to place a order with simple strategy, please spare some time and help me.

Hi @Hardik
I think issue is in Historical api for Futures scripts for 1 day timeframe only.
example : Learn Algo Trading with Python | Codes | Youtube Series - #2123 by Simardeep_Singh

1 Like

Hi, @mobile2024 , I am also not a developer nor the IT guy, @Tradehull_Imran sir has taught from basic to advance level for non coders. Just follow the those steps , you will end up in making Algo of your own.

1 Like

@Tradehull_Imran Sir,

Any update how to stop multiple orders after exiting trade.

Hi @Samis ,

Adding @Hardik for the same.

Hi @Arun_Rawat ,

For managing multiple orders we need to use orderbook structure.
Example:
orderbook[name]['exit_time'] = str(current_time.time())[:8]

We have added a tested framework for orderbook do apply this framework to your code also.

import pdb
import time
import datetime
import traceback
from Dhan_Tradehull import Tradehull
import pandas as pd
from pprint import pprint
import talib
import pandas_ta as ta
import xlwings as xw
import winsound



client_code = "1102790337"
token_id    = "bhgvsaoieqhjvhg"
tsl         = Tradehull(client_code,token_id)

# Uncomment below code to do pre market scanning
# pre_market_watchlist        = ['ASIANPAINT', 'BAJAJ-AUTO', 'BERGEPAINT', 'BEL', 'BOSCHLTD', 'BRITANNIA', 'COALINDIA', 'COLPAL', 'DABUR', 'DIVISLAB', 'EICHERMOT', 'GODREJCP', 'HCLTECH', 'HDFCBANK', 'HAVELLS', 'HEROMOTOCO', 'HAL', 'HINDUNILVR', 'ITC', 'IRCTC', 'INFY', 'LTIM', 'MARICO', 'MARUTI', 'NESTLEIND', 'PIDILITIND', 'TCS', 'TECHM', 'WIPRO']
# watchlist                   = []

# for name in pre_market_watchlist:

# 	print("Pre market scanning ", name)
# 	day_chart = tsl.get_historical_data(tradingsymbol = name,exchange = 'NSE',timeframe="DAY")
# 	day_chart['upperband'], day_chart['middleband'], day_chart['lowerband'] = talib.BBANDS(day_chart['close'], timeperiod=20, nbdevup=2, nbdevdn=2, matype=0)


# 	last_day_candle = day_chart.iloc[-1]

# 	upper_breakout = last_day_candle['high'] > last_day_candle['upperband']
# 	lower_breakout = last_day_candle['low'] < last_day_candle['lowerband']

# 	if upper_breakout or lower_breakout:
# 		watchlist.append(name)
# 		print(f"\t selected {name} for trading")
# 		pdb.set_trace()


# print(watchlist)
# # pdb.set_trace()





watchlist = ['BEL', 'BOSCHLTD', 'COLPAL', 'HCLTECH', 'HDFCBANK', 'HAVELLS', 'HAL', 'ITC', 'IRCTC', 'INFY', 'LTIM', 'MARICO', 'MARUTI', 'NESTLEIND', 'PIDILITIND', 'TCS', 'TECHM', 'WIPRO']




single_order     = {'name':None, 'date':None , 'entry_time': None, 'entry_price': None, 'buy_sell': None, 'qty': None, 'sl': None, 'exit_time': None, 'exit_price': None, 'pnl': None, 'remark': None, 'traded':None}
orderbook        = {}
wb               = xw.Book('Live Trade Data.xlsx')
live_Trading     = wb.sheets['Live_Trading']
completed_orders_sheet = wb.sheets['completed_orders']
reentry          = "yes" #"yes/no"
completed_orders = []


bot_token        = "8059847390:AAECSnQK-yOaGJ-clJchb1cx8CDhx2VQq-M"
receiver_chat_id = "1918451082"


live_Trading.range("A2:Z100").value = None
completed_orders_sheet.range("A2:Z100").value = None

for name in watchlist:
	orderbook[name] = single_order.copy()



while True:

	print("starting while Loop \n\n")

	current_time = datetime.datetime.now().time()
	if current_time < datetime.time(13, 55):
		print(f"Wait for market to start", current_time)
		time.sleep(1)
		continue

	if current_time > datetime.time(15, 15):
		order_details = tsl.cancel_all_orders()
		print(f"Market over Closing all trades !! Bye Bye See you Tomorrow", current_time)
		pdb.set_trace()
		break


	all_ltp = tsl.get_ltp_data(names = watchlist)
	for name in watchlist:


		orderbook_df                       = pd.DataFrame(orderbook).T
		live_Trading.range('A1').value     = orderbook_df

		completed_orders_df                =  pd.DataFrame(completed_orders)
		completed_orders_sheet.range('A1').value = completed_orders_df


		current_time          = datetime.datetime.now()
		print(f"Scanning        {name} {current_time}")




		try:
			chart                 = tsl.get_historical_data(tradingsymbol = name,exchange = 'NSE',timeframe="5")
			chart['rsi']          = talib.RSI(chart['close'], timeperiod=14)
			cc  = chart.iloc[-2]

			# buy entry conditions
			bc1 = cc['rsi'] > 45
			bc2 = orderbook[name]['traded'] is None
		except Exception as e:
			print(e)
			continue



		if bc1 and bc2:
			print("buy ", name, "\t")

			margin_avialable = tsl.get_balance()
			margin_required  = cc['close']/4.5

			if margin_avialable < margin_required:
				print(f"Less margin, not taking order : margin_avialable is {margin_avialable} and margin_required is {margin_required} for {name}")
				continue


			orderbook[name]['name']           = name
			orderbook[name]['date']           = str(current_time.date())
			orderbook[name]['entry_time']     = str(current_time.time())[:8]
			orderbook[name]['buy_sell']       = "BUY"
			orderbook[name]['qty']            = 1


			try:
				entry_orderid                     = tsl.order_placement(tradingsymbol=name ,exchange='NSE', quantity=orderbook[name]['qty'], price=0, trigger_price=0,    order_type='MARKET',     transaction_type='BUY',   trade_type='MIS')
				orderbook[name]['entry_orderid']  = entry_orderid
				orderbook[name]['entry_price']    = tsl.get_executed_price(orderid=orderbook[name]['entry_orderid'])

				orderbook[name]['tg']             = round(orderbook[name]['entry_price']*1.002, 1)   # 1.01
				orderbook[name]['sl']             = round(orderbook[name]['entry_price']*0.998, 1)    # 99
				sl_orderid                        = tsl.order_placement(tradingsymbol=name ,exchange='NSE', quantity=orderbook[name]['qty'], price=0, trigger_price=orderbook[name]['sl'], order_type='STOPMARKET', transaction_type ='SELL', trade_type='MIS')
				orderbook[name]['sl_orderid']     = sl_orderid
				orderbook[name]['traded']         = "yes"

				message = "\n".join(f"'{key}': {repr(value)}" for key, value in orderbook[name].items())
				message = f"Entry_done {name} \n\n {message}"
				tsl.send_telegram_alert(message=message,receiver_chat_id=receiver_chat_id,bot_token=bot_token)



			except Exception as e:
				print(e)
				pdb.set_trace(header= "error in entry order")





		if orderbook[name]['traded'] == "yes":
			bought = orderbook[name]['buy_sell'] == "BUY"

			if bought:

				try:
					ltp       = all_ltp[name]
					sl_hit    = tsl.get_order_status(orderid=orderbook[name]['sl_orderid']) == "TRADED"
					tg_hit    = ltp > orderbook[name]['tg']
				except Exception as e:
					print(e)
					pdb.set_trace(header = "error in sl order cheking")



				if sl_hit:

					try:
						orderbook[name]['exit_time']  = str(current_time.time())[:8]
						orderbook[name]['exit_price'] = tsl.get_executed_price(orderid=orderbook[name]['sl_orderid'])
						orderbook[name]['pnl']        = round((orderbook[name]['exit_price'] - orderbook[name]['entry_price'])*orderbook[name]['qty'],1)
						orderbook[name]['remark']     = "Bought_SL_hit"

						message = "\n".join(f"'{key}': {repr(value)}" for key, value in orderbook[name].items())
						message = f"SL_HIT {name} \n\n {message}"
						tsl.send_telegram_alert(message=message,receiver_chat_id=receiver_chat_id,bot_token=bot_token)



						if reentry == "yes":
							completed_orders.append(orderbook[name])
							orderbook[name] = None
					except Exception as e:
						print(e)
						pdb.set_trace(header = "error in sl_hit")



				if tg_hit:

					try:
						tsl.cancel_order(OrderID=orderbook[name]['sl_orderid'])
						time.sleep(2)
						square_off_buy_order          = tsl.order_placement(tradingsymbol=orderbook[name]['name'] ,exchange='NSE', quantity=orderbook[name]['qty'], price=0, trigger_price=0,    order_type='MARKET',     transaction_type='SELL',   trade_type='MIS')

						orderbook[name]['exit_time']  = str(current_time.time())[:8]
						orderbook[name]['exit_price'] = tsl.get_executed_price(orderid=square_off_buy_order)
						orderbook[name]['pnl']        = (orderbook[name]['exit_price'] - orderbook[name]['entry_price'])*orderbook[name]['qty']
						orderbook[name]['remark']     = "Bought_TG_hit"

						message = "\n".join(f"'{key}': {repr(value)}" for key, value in orderbook[name].items())
						message = f"TG_HIT {name} \n\n {message}"
						tsl.send_telegram_alert(message=message,receiver_chat_id=receiver_chat_id,bot_token=bot_token)


						if reentry == "yes":
							completed_orders.append(orderbook[name])
							orderbook[name] = None

						winsound.Beep(1500, 10000)

					except Exception as e:
						print(e)
						pdb.set_trace(header = "error in tg_hit")







hii @Tradehull_Imran sir, what is this ishue

Hello @Tradehull_Imran Sir
Buy or Sell order ek sath me de rha hai …Please help

hii @Tradehull_Imran

I am attempting data_codebase usage.

import pdb
import time
import datetime
import traceback
import talib
from Dhan_Tradehull import Tradehull
import pandas as pd


client_code = "1105849834"
token_id = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJkaGFuIiwicGFydG5lcklkIjoiIiwiZXhwIjoxNzM2NDMxMDcwLCJ0b2tlbkNvbnN1bWVyVHlwZSI6IlNFTEYiLCJ3ZWJob29rVXJsIjoiaHR0cHM6Ly93ZWIuZGhhbi5jby9pbmRleC9wcm9maWxlIiwiZGhhbkNsaWVudElkIjoiMTEwNTg0OTgzNCJ9.2a1iEONitWp9VkXT6gK9yj5lwrOtaJIrDb4o184VusNxPvBSFIix3-u4nGJHy6C5CIYRJk9WN-X4ENAOHlcBlg"
tsl = Tradehull(client_code,token_id) # tradehull_support_library

pdb.set_trace()

tsl.get_intraday_data('ACC','NSE',1)

tsl.get_intraday_data('NIFTY','NSE',1)


available_balance = tsl.get_balance()
max_risk_for_the_day = (available_balance*1)/100*-1
print("available_balance", available_balance)

ltp1 = tsl.get_ltp('ACC')
ltp2 = tsl.get_ltp('NIFTY')
ltp3 = tsl.get_ltp('BANKNIFTY 28 AUG 51600 CALL')
ltp4 = tsl.get_ltp('NIFTY 29 AUG 23200 CALL')

previous_hist_data = tsl.get_historical_data('ACC','NSE',12)
intraday_hist_data = tsl.get_intraday_data('ACC','NSE',1)



ce_name, pe_name, strike = tsl.ATM_Strike_Selection('NIFTY','05-09-2024')
otm_ce_name, pe_name, ce_OTM_strike, pe_OTM_strike = tsl.OTM_Strike_Selection('NIFTY','05-09-2024',3)
ce_name, pe_name, ce_ITM_strike, pe_ITM_strike = tsl.ITM_Strike_Selection('NIFTY','05-09-2024', 4)


intraday_hist_data = tsl.get_intraday_data(otm_ce_name,'NFO',1)
intraday_hist_data['rsi'] = talib.RSI(intraday_hist_data['close'], timeperiod=14)


lot_size = tsl.get_lot_size('NIFTY 29 AUG 24500 CALL')
lot_size = tsl.get_lot_size(otm_ce_name)
qty = 2*lot_size

# next lecture
orderid1 = tsl.order_placement('NIFTY 29 AUG 24500 CALL','NFO',25, 0.05, 0, 'LIMIT', 'BUY', 'MIS')
orderid2 = tsl.order_placement('BANKNIFTY 28 AUG 51600 CALL','NFO',15, 0.05, 0, 'LIMIT', 'BUY', 'MIS')
orderid3 = tsl.order_placement('ACC','NSE', 1, 0, 0, 'MARKET', 'BUY', 'MIS')
exit_all = tsl.cancel_all_orders()
















live_pnl = tsl.get_live_pnl()
if live_pnl < max_risk_for_the_day:
	exit_all = tsl.cancel_all_orders()
	response = tsl.kill_switch('ON')

error


Traceback (most recent call last):
  File "C:\Users\kedar\OneDrive\Desktop\Tradehull Dhan algo Trading Course\3. Session3 - Codebase\3. Session3 - Codebase\Dhan codebase\Dhan_codebase usage.py", line 5, in <module>
    import talib
ModuleNotFoundError: No module named 'talib'
[Finished in 184ms]

Hi @Hardik Sir,

Please look into this Rate limit errors while fetching the OHLC candle data for the symbols, per day limit it getting hit, even if the WATCHLIST have 100 symbols as we are using 1 Data API call for each symbol to fetch the OHLC data.

If Dhan Data API support to fetch OHLC data for multiple symbols in a single t call then that will be very useful to avoid this rate limit errors,
we can run single API for a 5 minutes to get the 5Minutes candle data for multiple stocks in one go.
I have raised this request to Dhan helpdesk as well, please extend the historical_data() to support the list of symbols of same exchange as input.

Looking forward for your support.

2 Likes

@Tradehull_Imran Sir, I would like to understand why I received this error.

I am ready

1 Like

@Tradehull_Imran

Fetch Option Chain Data

    options_data = tsl.get_option_chain(symbol='BANKNIFTY', expiry='30-01-2025')
    highest_call_oi, highest_put_oi = get_highest_oi(options_data) 

THIS SCRIPT HAVING SOME ISSUE
Error: get_option_chain() got an unexpected keyword argument ‘symbol’
CAN YOU PLEASE CORRECT ME HOW TO SOLVE THIS ISSUE.

ALSO PLEASE LET MY KNOW HOW TO FIND PCR DATA.

Equity Buy/Sell : with Candle stick pattern + trendline + Dow theory (without indicator)

  1. Select a time like D,W,M,1H,15Mins, 30Mins, 5Mins
  2. Define a range 10Years, 5Years, 6Months, 3Months, 1Weeks, 1Day
    3.Define range and Time frame
    i) Till now what are the swing high or low
    Sell condition
    ii) Find others major swings ( how many swings we can take we can give the input)
  3. Find market currently uptrend or down trend with Dow theory and swing trendlines
  4. Need to define which bullish or bearish candle patterns we want to include

6.In define time range we have to find out market is bottom most or top most
If top most I will try to find out is there any bearish candle pattern making or not.
7. If we get suitable pattern then I will wait for 1st Lower high(swing) and when It will break 1st higher low I will sell my position

  1. we can use trendline Breakdown also for additional confirmation

@Tradehull_Imran sir basic one I will improve more

2 Likes

hey everyone i am trying to fetch Connecting to market feed…
Market feed connected.
Failed to fetch LTP for Security ID 1333. Status Code: 401, Response: {“Data”:{“810”:“ClientId is invalid”},“status”:“failed”}
Failed to fetch LTP for Security ID 532540. Status Code: 401, Response: {“Data”:{“810”:“ClientId is invalid”},“status”:“failed”}
Failed to fetch LTP for Security ID 1333. Status Code: 401, Response: {“Data”:{“810”:“ClientId is invalid”},“status”:“failed”}
Failed to fetch LTP for Security ID 532540. Status Code: 401, Response: {“Data”:{“810”:“ClientId is invalid”},“status”:“failed”}
Failed to fetch LTP for Security ID 1333. Status Code: 401, Response: {“Data”:{“810”:“ClientId is invalid”},“status”:“failed”}
Failed to fetch LTP for Security ID 532540. Status Code: 401, Response: {“Data”:{"810 and getting this error

although i have double check my credentials are correct