Learn Algo Trading with Python | Codes | Youtube Series

Hi, @Tradehull_Imran , I have tried my level best to make a alog with the help of API Trades Meetup&Workshop files, Please check it from your end , Sir, because Squareoff Order is not placing when tg_hit = ltp > orderbook[name]['tg']

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        = {}
reentry          = "yes"
completed_orders = []

#-----------------------------------------------------------------------------------------------------
all_ltp = tsl.get_ltp_data(watchlist)

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

while True:
	live_pnl = tsl.get_live_pnl()
	current_time = datetime.datetime.now().time()


	if current_time < datetime.time(9, 00):
		print("Wait for market to start", current_time)
		time.sleep(1)
		continue

	if (current_time > datetime.time(23, 59)) or (live_pnl < max_loss):
		order_details = tsl.cancel_all_orders()
		print("Market is over, Bye Bye see you tomorrow", current_time)
		#pdb.set_trace()
		break

	for name in watchlist:
		current_time          = datetime.datetime.now()
		print(f"Scanning {name} {current_time}")
		ltp     = all_ltp[name]

		try:
			chart                 = tsl.get_historical_data(tradingsymbol = name,exchange = 'NSE',timeframe="1")
			chart['rsi']          = talib.RSI(chart['close'], timeperiod=14)
			chart['ma_small']     = talib.MA(chart['close'], timeperiod=14)
			chart['ma_big']       = talib.MA(chart['close'], timeperiod=21)


			cc  = chart.iloc[-2]
			bc1 = cc['rsi'] > 25
			bc2 = cc['ma_small'] > cc['ma_big']
			bc3 = orderbook[name]['traded'] is None

		except Exception as e:
			print(e)
			continue

		if bc1 and bc2 and bc3:

			print("buy", name, "\t")
			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    					#int(10000/ltp)


			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"
			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"

						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"

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

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

Good evening @Tradehull_Imran Sir
rate limit issue aa gya hai code run nahi ho pa rha
kya kre

Hi @vinay_kumaar
For the rate limits, use the newer version of codebase

latest codebase file : Dhan_Tradehull_V2.py - Google Drive

Hi @Kishore007
I will test the same, in live markets.

1 Like

Hello @Tradehull_Imran ,

Recently I am getting error in Dhan_Tradehull_V2.py


Import “dhanhq” could not be resolved Pylance

I tried to reinstall “install libraries.bat” file. Here also I am getting below error.

Can you identify the exact reason behind this issue?

Thanks,
Sudip

Hi @Tradehull_Imran Sir
Error aa rha hai…

Exception for instrument name NIFTY DEC FUT  as Check the Tradingsymbol
Exception at calling ltp as {'status': 'failure', 'remarks': 'Expecting value: line 1 column 1 (char 0)', 'data': ''}
Traceback (most recent call last):

getting same error as above

Hi @SUDIP_NATH

This error is because the code is using python version 3.1.1, which is not compatible with twisted and talib which wants version of 3.8.0

Do uninstall python 3.1.1 and python launcher from control panel and install version 3.8.0

Explanation

Hi @vinay_kumaar @Rajashekhar_Rangappa

there seems to be some issue with the ltp call, most probably I think this maybe the impact of market not open. will need to try the same LTP call tomorrow

Also other than LTP and LTP dependent functions, remaining api calls such as historical data seems to be working fine

@Tradehull_Imran @Rajashekhar_Rangappa
Dhan Care say
If you’re trying to fetch the LTP for the current time, the request will fail as the markets are closed today…
pahle close market me bhi work kar rha tha…

Hi @vinay_kumaar

I am not completely sure as of now on what may be the root issue.
Let wait till market open tomorrow to investigate the issue in detail.

@Tradehull_Imran

Can you please provide support for trailing stop loss order.

Idea is to place SL order once and use this feature of dhan.

We just need to pass trailing jump point.

I see you provide reference for nfo but i am looking for equity.

Hi everyone,

This is a project that I am working on,
Backtesting can hep us to analyze various trailing_stoploss methods

6 Likes

Hi @virender_singh

lets check this on tomorrow.

2 Likes

Great Sir,

If we could implement it, it would help us a lot!

Waiting for your advanced series.

1 Like

Amazing

1 Like

import pdb
from Dhan_Tradehull_V2 import Tradehull
import talib
import time
import datetime
client_code = “…”
token_id =“…”

Initialize Tradehull Client

tsl = Tradehull(client_code, token_id)

chart= tsl.get_historical_data(‘SENSEX 27 DEC 78500 CALL’, exchange=‘BFO’, timeframe=“5”)
#chart1= tsl.get_historical_data(‘NIFTY 26 DEC 23650 PUT’, exchange=‘NFO’, timeframe=“5”)
pdb.set_trace()

Hello Sir,
I am using the above code to get historical data for option strike pertaining BSE exchange, has anyone tried to get the data of BSE exchange option strike. It is working fine for NSE. I am getting error for the above code
Exception in Getting OHLC data as {‘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’}}

I am getting ltp, ATM, ITM, OTM strike selection, etc for the BSE option script but not able to get OHLC data.

KINDLY SUGGEST A SOLUTION.

Hi @Tradehull_Imran @Dhan
Data not receved

Error massege -  index_ltp      = tsl.get_ltp_data(names = ['NIFTY DEC FUT '])['NIFTY DEC FUT']      
KeyError: 'NIFTY DEC FUT'

Hello Everyone,

I am new to API & Programming. So somebody help me to check what’s wrong with the code I wrote. Nothing shows (Please check the screenshot)

Hi @vinay_kumaar

in the code, there is a extra space bar after NIFTY DEC FUT SPACEBAR

tsl.get_ltp_data(names = ['NIFTY DEC FUT '])['NIFTY DEC FUT']

Correct code

ltp   = tsl.get_ltp_data(names = ['NIFTY DEC FUT'])['NIFTY DEC FUT']