Learn Algo Trading with Python | Codes | Youtube Series

Can you check the case today for Bracket order for scalping strategy

Hi @Aijaz_Ahmad

Backtesting is an advanced concept that requires a deep understanding of codes. I plan to cover it gradually as we advance.

1 Like

Hi @Jyothi_Chilukoti

use tsl.get_historical_data()

Do not use tsl.get_intraday_data(), we will be removing this function in future.

1 Like

Hi @Kalpeshh_Patel
Share the complete code you are using,

This portion is okey, error seems to be somewhere else

if (index_chart == None):
    time.sleep(60)
    continue

Hi Folks,

Episode 8 is out, and many of you might have already tuned in!

Just a heads-up—only two more episodes remain in this series.

The incredible interest and enthusiasm we’ve seen from all of you have been truly inspiring, and we’re excited to bring even more engaging content your way.

We’d love to hear your suggestions: What would you like to learn next?

Let us know your thoughts!

2 Likes

Hi
@Tradehull_Imran
Here I am attaching my file
Please do correction
There are two errors
1 if (index_chart == None):
** time.sleep(60)**
** continue**
C:\Algo Practice\Session 8>py “2 candle theory Algo - Both Side Pseudocode V2.py”
File “2 candle theory Algo - Both Side Pseudocode V2.py”, line 37
if (index_chart == None):
^
SyntaxError: invalid syntax

2. - ltp not detected
C:\Algo Practice\Session 8>py “RSI Option V2.py”
Codebase Version 2.1
-----Logged into Dhan-----
reading existing file all_instrument 2024-11-25.csv
Got the instrument file
available_balance 275667.47
BUY 09:55:23.121570 True False False cc_1 09:45:00
SELL 09:55:23.121570 True True True cc_1 09:45:00

NIFTY NOV FUT Buy PUT
Traceback (most recent call last):
File “RSI Option V2.py”, line 146, in
price_has_moved_20_pct = ltp > (trade_info[‘entry_price’])*1.2
NameError: name ‘ltp’ is not defined



Hi @Scooby_Doo

If we keep keep the SL and Target very close, the order is rejected by Dhan Risk Management System.
Actually, this is a good feature from Risk perspective.

However , if you want to scalp, use Cover/LIMIT or Trigger orders.

see : BO.mp4 - Google Drive

Hi @Kalpeshh_Patel

  1. we can use index_ltp instead of just ltp (as this variable was never defined)

  2. We need to check if chart data is empty for both
    index_chart_5 and index_chart

  3. Till now we have not studied how to manage multiple scripts in Algo. There is a framework to it that I will need to teach before it can be implementeed, so I have removed for loop from code.

  4. Do not post your credentials while submitting code on forum

import pdb
import traceback
import time
import datetime
from Dhan_Tradehull_V2 import Tradehull
import pandas as pd
from pprint import pprint
import pandas_ta as pta
import talib
import pandas_ta as ta
import warnings

warnings.filterwarnings("ignore")


# ---------------for dhan login ----------------

client_code = "xxxxxxxxx"
token_id = "xxxxxxxx"

tsl 	= Tradehull(client_code,token_id)

available_balance = tsl.get_balance()

print("available_balance", available_balance)

index_name = 'BANKNIFTY NOV FUT'
traded = "no"
trade_info = {"options_name":None, "qty":None, "sl":None, "CE_PE":None, "entry_price":None ,  "Trailed":None}


while True:

	current_time = datetime.datetime.now().time()

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

	if (current_time > datetime.time(23, 25)):
		print("Market is over, Bye Bye see you tomorrow", current_time)
		break

	index_chart         = tsl.get_historical_data(tradingsymbol=index_name, exchange='NFO', timeframe="15")
	time.sleep(3)
	index_chart_5	    = tsl.get_historical_data(tradingsymbol = index_name,exchange = 'NFO',timeframe="5")
	index_ltp    = tsl.get_ltp_data(names = ['NIFTY NOV FUT','BANKNIFTY NOV FUT'])

	if index_chart.empty or index_chart_5.empty:
		time.sleep(60)
		continue

	index_chart['rsi']	= talib.RSI(index_chart['close'], timeperiod=14) #pandas
	supertrend		    = ta.supertrend(index_chart_5['high'], index_chart_5['low'], index_chart_5['close'], 10, 3)
	index_chart_5     	= pd.concat([index_chart_5, supertrend], axis=1, join='inner')



	pdb.set_trace()

	# time.sleep(60)
	# continue
		# print(index_chart,'scanning',)

		
	cc_1	= index_chart.iloc[-1]  #pandas  completed candle of 15 min timeframe
	cc_2	= index_chart.iloc[-2]
	cc_3	= index_chart.iloc[-3]
	cc5_2	= index_chart_5.iloc[-2]

	
		# ---------------------------- BUY ENTRY CONDITIONS ----------------------------
		
	up1	= cc_2['rsi'] > 60
	up2	= cc_3['rsi'] < 60
	up3	= cc_2['high'] < cc_1['close']
	print(f"BUY\t {current_time} \t {up1} \t {up2} \t {up3} \t cc_1 {str(cc_1['timestamp'].time())}")
	# pdb.set_trace()
	

		# ---------------------------- SELL ENTRY CONDITIONS ----------------------------
	dt1	= cc_2['rsi'] < 90 # This is for tral basis
	dt2	= cc_3['rsi'] > 90 # This is for tral basis
	dt3	= cc_2['low'] > cc_1['close']
	print(f"SELL\t {current_time} \t {dt1} \t {dt2} \t {dt3} \t cc_1 {str(cc_1['timestamp'].time())} \n")

	if up1 and up2 and up3:
	
		print(index_name, "Buy CALL")
		
		ce_name, pe_name, strike   = tsl.ATM_Strike_Selection(Underlying ='NIFTY',Expiry ='28-11-2024')
		lot_size                   = tsl.get_lot_size(ce_name)*1
		entry_orderid              = tsl.order_placement(ce_name,'NFO', lot_size, 0, 0, 'MARKET', 'BUY', 'MIS')
		traded                     = "yes"
		trade_info['options_name'] = ce_name
		trade_info['qty']          = lot_size
		trade_info['sl']           = cc_2['low']
		trade_info['CE_PE']        = "CE"

		time.sleep(1)
		trade_info['entry_price'] = tsl.get_executed_price(orderid=trade_info['entry_orderid'])



	if dt1 and dt2 and dt3:
		print(index_name, "Buy PUT")
		
		ce_name, pe_name, strike   = tsl.ATM_Strike_Selection(Underlying ='NIFTY',Expiry ='28-11-2024')
		lot_size                   = tsl.get_lot_size(pe_name)*1
		entry_orderid              = tsl.order_placement(pe_name,'NFO', lot_size, 0, 0, 'MARKET', 'BUY', 'MIS')
		traded                     = "yes"
		trade_info['options_name'] = pe_name
		trade_info['qty']          = lot_size
		trade_info['sl']           = cc_2['high']
		trade_info['CE_PE']        = "PE"

		# ---------------------------- check for exit SL/TG

	if traded == "yes":

		long_position  = trade_info['CE_PE'] == "CE"
		short_position = trade_info['CE_PE'] == "PE"


		if long_position:

			price_has_moved_20_pct        = index_ltp > (trade_info['entry_price'])*1.2
			position_has_not_been_trailed = trade_info['Trailed'] is None
	
			if price_has_moved_20_pct and position_has_not_been_trailed:
				trade_info['sl']           = trade_info['entry_price']
				trade_info['Trailed']      = "yes_I_have_trailed"


			sl_hit = index_ltp < trade_info['sl']
			tg_hit = index_ltp < cc5_2['SUPERT_10_3.0']

			if sl_hit or tg_hit:
				print("Order Exited", trade_info)
				exit_orderid        = tsl.order_placement(trade_info['options_name'],'NFO', trade_info['qty'], 0, 0, 'MARKET', 'SELL', 'MIS')
				# pdb.set_trace()


		if short_position:

			price_has_moved_20_pct        = index_ltp > (trade_info['entry_price'])*1.2
			position_has_not_been_trailed = trade_info['Trailed'] is None
	
			if price_has_moved_20_pct and position_has_not_been_trailed:
				trade_info['sl']           = trade_info['entry_price']
				trade_info['Trailed']      = "yes_I_have_trailed"


			sl_hit = index_ltp < trade_info['sl']
			tg_hit = index_ltp < cc5_2['SUPERT_10_3.0']

			if sl_hit or tg_hit:
				print("Order Exited", trade_info)
				exit_orderid        = tsl.order_placement(trade_info['options_name'],'NFO', trade_info['qty'], 0, 0, 'MARKET', 'SELL', 'MIS')
				# pdb.set_trace()

Hi @Tradehull_Imran,

Even I am facing the same issue, If I use BO then I get same error and If I use CO it only allows you to place SL only and not target.

Hi
@Tradehull_Imran

I understand
So
Can you please delete this file
If Possible

1 Like

Hello @Tradehull_Imran
How do i Get order id of the last trade executed?

Hi everyone, @Francis_Antony

If you are new to the series and watching it from start, do follow this sequence.
This will help you to upgrade to all the latest changes.

Code Name Video Link Activity to complete
1. Session1 - Introduction https://www.youtube.com/watch?v=4QmdVg2pPGs No action
2. Session2 - Installation https://www.youtube.com/watch?v=YAyIoDJYorA complete the installtion
3. Session3 - Codebase https://www.youtube.com/watch?v=DPWU5wLuYcQ No action, just study the video
Dhan_Tradehull_V2 and Upgraded LTP https://www.youtube.com/watch?v=HLiEpNZSD80 Practice code given,
4. Session4- Python Part 1 https://www.youtube.com/watch?v=9KicRvYFLlU all concepts practice
5. Session5- Python Part 2 https://www.youtube.com/watch?v=_UKH2mml_Dg practice the code for Ltp Based Strike Selection using Dhan_Tradehull_V2
6. Session6- 1st Live Algo https://www.youtube.com/watch?v=bF6IjRumWZE Practice the algo
7. Session7- Python Basics Part 3 https://www.youtube.com/watch?v=cZ3twt8ZScc Practice code
8. Session8- 2nd Live Algo https://www.youtube.com/watch?v=fnmHrmWgBh0 Implement multitimeframe algo
9. Session9- 3rd Live Algo https://www.youtube.com/watch?v=5qw8GLFxu98 Implement breakout algo
1 Like

Hi @Aijaz_Ahmad

You can use Cover Orders and Targets can be placed in memory,
this way target is not sent to Dhan, its stored only in python memory, when the ltp crosses the target level, we will send the exit order.

Like this,


	if traded == "yes":

		long_position  = trade_info['CE_PE'] == "CE"
		short_position = trade_info['CE_PE'] == "PE"


		if long_position:
			sl_hit = tsl.get_order_status(orderid=trade_info['entry_orderid'])
			tg_hit = index_ltp > trade_info['tg']

			if sl_hit
				print("Target Hit", trade_info)
				pdb.set_trace()

			if tg_hit:
				print("Target Hit", trade_info)
				exit_orderid        = tsl.order_placement(trade_info['options_name'],'NFO', trade_info['qty'], 0, 0, 'MARKET', 'SELL', 'MIS')
				pdb.set_trace()




Hi @Scooby_Doo
use below code

orderbook = tsl.get_orderbook()
orderbook = pd.DataFrame(orderbook)

last_trade = orderbook.iloc[0]
last_trade_orderid = last_trade['orderId']

Hi @Naga_Rajesh_K

We can now fetch data for BFO as well

see : BFO ISSUE.zip - Google Drive

1 Like

Hi @Tradehull_Imran,

But if we use CO then won’t we need to continously check LTP if the target is reached, also can u please share CO code?

Also, won’t it create rate limt issue if we continously check LTP.

I am unable to get ce_name, pe_name

Message: 'Got exception in ce_pe_option_df ’
Arguments: (KeyError(‘NIFTY’),)
exception got in ce_pe_option_df ‘NIFTY’
Traceback (most recent call last):
File “/home/mohan/Dhan-Alog-Trading/examples/Dhan_Tradehull_V2.py”, line 513, in ATM_Strike_Selection
ltp = ltp_data[Underlying]
~~~~~~~~^^^^^^^^^^^^
KeyError: ‘NIFTY’

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File “/home/mohan/Dhan-Alog-Trading/examples/mydemo.py”, line 19, in
ce_name, pe_name, strike = tsl.ATM_Strike_Selection(Underlying =‘NIFTY’,Expiry =‘28-11-2024’)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “/home/mohan/Dhan-Alog-Trading/examples/Dhan_Tradehull_V2.py”, line 568, in ATM_Strike_Selection
return None, None, strike
^^^^^^
UnboundLocalError: cannot access local variable ‘strike’ where it is not associated with a value

Hello @Tradehull_Imran,

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

1 Like

Hi
@Tradehull_Imran
I deploy the algo
But
After trade execute it gives error

NIFTY NOV FUT Buy CALL
Traceback (most recent call last):
File “RSI Option V3.py”, line 101, in
trade_info[‘entry_price’] = tsl.get_executed_price(orderid=trade_info[‘entry_orderid’])
KeyError: ‘entry_orderid’


And while I start again algo
For same candle order once again execute

Please solve the error

Thank you

Hi @thakurmhn

this code seems to be working fine on my end

ce_name, pe_name, strike = tsl.ATM_Strike_Selection(Underlying ='NIFTY',Expiry ='28-11-2024')

  1. Do share the complete files
  2. also send the output for pip show dhanhq