Learn Algo Trading with Python | Codes | Youtube Series

Hi @Aijaz_Ahmad

  1. Try the code for CO once at your end, if any error do send it
    Take reference from the bracket order code,
    reference : Learn Algo Trading with Python | Codes | Youtube Series - #983 by Tradehull_Imran

  2. It can be made such rate limit issue does not arise, we can call LTP in bulk.
    example : tsl.get_ltp_data(names = ["NIFTY 28 NOV 23500 CALL", "NIFTY 28 NOV 23550 CALL", "NIFTY 28 NOV 23600 CALL", "NIFTY 28 NOV 23650 CALL", "NIFTY 28 NOV 23700 CALL"])

also if rate limits becomes a issue even after it, we can place a target order separately

hi sir
level ka breakout code kya hoga please help

Hi @rahulcse56
Yes this data is correct, Thanks for the observation.

Hi @Kalpeshh_Patel

Also for the pseudocode, do carefully fill in any gaps, fix any errors, and implement it into a working program.
Also same changes needs to be made PE side as well.

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, "entry_orderid":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"
		trade_info['entry_orderid']= entry_orderid

		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()

levels = {
“level1”: 50882.45,
“level2”: 50657.50,
“level3”: 50531.00,
“level4”: 50361.85,
“level5”: 50358.00,
“level6”: 50355.05,
“level7”: 50225.40,
“level8”: 50113.00,
“level9”: 50082.50,
“level10”: 50070.85,
“level11”: 49915.80
}

hi sir
level ka breakout code kya hoga please help

Hi @avinashkumar07412

For Breakout code see this session 9 reference video : https://www.youtube.com/watch?v=5qw8GLFxu98

@Subhajitpanja @Kalpeshh_Patel @rahulcse56 @Zee2Zahid @Aijaz_Ahmad @Jyothi_Chilukoti @Md_Naquibuddin @Manish_Goel @Khandu_Kshirsagar @ddeogharkar

What would you like to learn next. Do submit your topics here.

@Kishore007 @Kuldeep_Khaladkar @thakurmhn @Vijen_Singh @jain79 @Hitesh_Maurya @Siddhesh_Amrute @CBrid @ramakriishna @Gautam_Singh_Pawar

What would you like to learn next. Do submit your Topics.

@everyone @pratik_patil2 @Abhishek_Konda

What would you like to learn next. Do submit your Topics.

@RahulDeshpande @Tradehull_Imran

options back testing series is needed, also how to send telegram alerts and deploy to server

1 Like

Hello @Tradehull_Imran sir,
I have written this code and would really appreciate it if you could review it.
I am a little dicey about the MODIFY ORDER function call.

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

client_code = “1100578034”
token_id = “ekaGFuIiwicGFydG5lcklkIjoiIiwiZXhwIjoxNzM0OTM0ODA5LCJ0b2tlbkNvbnN1bWVyVHlwZSI6IlNFTEYiLCJ3ZWJob29rVXJsIjoiIiwiZGhhbkNsaWVudElkIjoiMTEwMDU3ODAzNCJ9.uZdu-TkAGdg0NulMY5DWb9v1BPyClGYygmTfLxXvkxzx0bp5yVkU0l_HQymYdcdFEvPvWXmK8KNL5iCjInQdtw”
tsl = Tradehull(client_code,token_id)

Trading parameters

options_name = “NIFTY 28 NOV 24200 CALL”
qty_lots = 25 # Lot size
target_points = 35 # Target in points
sl_points = 25 # Stop-loss in points
limit_price_order = 196.5 #higher than trigger
trigger_price_order = 196 #lower than limit
order_type = “STOPLIMIT”

Get current LTP (Last Traded Price)

fno_ltp = tsl.get_ltp_data(“NIFTY 28 NOV 24200 CALL”)

traded = “no”
trade_info = {“options_name”: None, “qty”: None, “sl”: None}

while True:
try:
# Get current time
current_time = datetime.datetime.now()

    # Fetch historical data
    fno_chart = tsl.get_historical_data(tradingsymbol=options_name, exchange="NFO", timeframe="1" )
    time.sleep(3)

    # Get current LTP (Last Traded Price)
    fno_ltp = tsl.get_ltp_data(options_name) 
    
    # Handle missing data
    if fno_chart is None or fno_ltp is None:
        print("Data unavailable. Retrying...")
        time.sleep(60)
        continue

    # Place a trade if no trade is active
    if traded == "no":
        # Place a Buy Order
        buy_entry_orderid = tsl.order_placement(options_name, "NFO", qty_lots, limit_price_order, trigger_price_order,order_type,"BUY", "MIS")
        print("BUY ORDER EXECUTED")
        traded = "yes"

        # Get executed price
        #order_price_response = tsl.get_executed_price(orderid=buy_entry_orderid)
        #pprint(order_price_response)

        #executed_price = order_price_response ("executed_price", 0)
        #executed_price = data.get('price', 0.0)
        executed_price = tsl.get_executed_price(orderid=buy_entry_orderid)
        if executed_price == 0:
            print("Error fetching executed price. Skipping trade.")
            traded = "no"
            continue

        # Place Stop-Loss Order Immediately
        sl_price_trigger = executed_price - sl_points
        sl_price_limit = sl_price_trigger - 1
        tsl.order_placement(options_name,"NFO", qty_lots, sl_price_limit, sl_price_trigger, "STOPLIMIT",  "SELL", "MIS",)
        print("SL Order Placed Immediately.")

    # Monitor for Target Exit
    if traded == "yes":
        tg_hit = fno_ltp > round((executed_price + target_points), 1)
        if tg_hit:
            print("Target Hit. Exiting Trade.")
            tsl.modify_order(appOrderID=buy_entry_orderid ,modifiedOrderType='MARKET', modifiedOrderQuantity=qty_lots, modifiedLimitPrice=0, modifiedStopPrice=0, trade_type='MIS')
            
            traded = "no"
            print("Exited Trade at Target.")
            pdb.set_trace()  # Debugging

except Exception as e:
    print(f"Error occurred: {e}")
    traceback.print_exc()
    time.sleep(60)

Looking forward to your response suggesting the exact changes needed.
Best Regards

# ------------------------- LEVELS----------------------------------------------------

levels = {
“level1”: 50882.45,
“level2”: 50657.50,
“level3”: 50531.00,
“level4”: 50361.85,
“level5”: 50358.00,
“level6”: 50355.05,
“level7”: 50225.40,
“level8”: 50113.00,
“level9”: 50082.50,
“level10”: 50070.85,
“level11”: 49915.80
}

chart_5 = tsl.get_historical_data(tradingsymbol=‘NIFTY NOV FUT’, exchange=‘NFO’, timeframe=“5”)
cc_5 = chart_5.iloc[-1]
breakout_c1 = cc_5[‘close’] > index_chart[levels.items()]

Hi
@Tradehull_Imran
I want to learn

  1. How to apply multi option stratagy with multi index in a single algo
  2. How to split over positions and book partial profit and remaining position with trailing SL
  3. How to use any common database/pickle/HDF5 for two strategy and send our data frame to it for both algo strategy can read from the same source.
1 Like

tagging @RahulDeshpande

hi @Tradehull_Imran , sir
Sir, Please me to complete this code.

# Place buy order
				entry_orderid = tsl.order_placement(stock_name, 'MCX', lot_size, 0, 0, 'MARKET', 'BUY', 'MIS')
				sl_orderid = tsl.order_placement(stock_name, 'MCX', lot_size, 0, sl_price, 'STOPMARKET', 'SELL', 'MIS')
				tp_orderid = tsl.order_placement(stock_name, 'MCX', lot_size, tp_price, 0, 'LIMIT', 'SELL', 'MIS')

				traded_wathclist.append(stock_name)

When TP or SL order has been traded then other trade should be cancelled and the stock should be removed from traded watchlist.

Please help me in completing the code, sir…

I am interested in learning to trade with Excel, this topic will be more interesting for me.

According to Session 9, Youtube video
All the watchlist and tarde_info like Direction - buy or sell based on support and resistance level in excel sheets.

in excel sheet , it will be easy to add 20 stocks and their levels .

2 Likes
api = dhanhq
required_people_intrested = (100 // 6)
url = "https://madefortrade.in/t/learn-algo-trading-with-python-codes-youtube-series/32718"
people_intrested = madefortrade.get_live_data(url)


if people_intrested > required_people_intrested:
	print("🔴 BUILD ALGO LIVE SESSION ON YOUTUBE")
	print("🔴 LIVE QUESTIONS AND ANSWER IMPLEMENTATION")
else:
	print("Wait ⏳")


print("SEND ME YOUR ANSWER IN CODE")
2 Likes

@Tradehull_Imran sir i am getting 2 error on both codebase & websocket. please check


Hi Imran sir,
Please give us a code where the position can be squareoff based on order ID capture during the order entry.
tsl.order_placement mayhave a field to enter the orderId of the position to squareoff existing positions.
Please help me with the code to squareoff the existing positions…
thanks for your valuable support.

You can spot me in the blue shirt. At that moment, both @RahulDeshpande and @Naman assured me they were already working on high-quality algorithmic content with an excellent teacher. They also promised that any future modifications needed would be taken care of.

Now, we can see the results of their efforts.

@Dhan stands out as the first broker genuinely committed to retail education, providing high-quality content delivered by exceptional teachers. Moreover, Dhan closely monitors our progress and identifies areas where we need to improve, ensuring we have the necessary resources to enhance our learning experience.

Our teacher’s (@Tradehull_Imran sir) commitment is truly unparalleled. He addresses every request personally, offering solutions and even suggesting additional resources to help us succeed. His dedication has made our educational section the most active and engaging part of the MadeForTrade community.

It’s a small token of gratitude to say thank you to Dhan for their forward-thinking approach to education and for finding the best algorithmic trading teacher, who generously shares his knowledge for free on their YouTube channel.

Next Session

Now, let’s talk about the next session. I have already requested some new features, which have been noted by our respected sir.

Sir, if I am not wrong, you have already requested more historical data for back testing from Dhan, and from my side, I have requested an increase in the API data limit per day( @Hardik ). Apart from that:

  1. Trade Tracking in Excel: We can keep track of our trades in an Excel sheet (once a trade is executed, all details will be noted in the sheet). The columns should include:
  • Date + Time
  • Name (e.g., Nifty, Crude Oil)
  • Strategy Name
  • Entry
  • Exit
  • Stop-Loss
  • Status (e.g., Profit/Loss) + Amount
  • Initial Capital
  • Current Capital
  1. Forward Testing: Similar to real trades, we can perform virtual trades with the same columns mentioned above. This will allow us to calculate from Excel which strategies are profitable or loss-making and by how much.

  2. Trendline Analysis by Algorithm: It should be possible to check if there is any slope trendline in the (D, W, M) time frame using an algorithm.

  • Identify resistance and support using trendlines(slope and horizontal).
  • Detect if there are any bullish or bearish patterns forming near support or resistance (initial examples can be provided, and students like us can contribute more).
  • Utilize RSI and MACD values (this part is already done, as I know).
  1. Dhan or Free NSE API:
  • Check which stocks are under FNO ban for the day (in Excel).
  • Dynamically update the list of FNO Nifty 50 stocks in Excel.
  • Identify stocks under the ASM ban list.

5.How to make combine strategy [with one example]
like Nifty, Release, Silver, stock with following parameter
we will try to create bearish strategy from that

    1. near support or breakout
  • 2.long build up
  • 3.OI put side oi increasing
  • 4.Bullish candle pattern with[ like bullish engulfing please create a scope whare we can add more by our choice]
    1. RSI + MACD

Previous Requests links

Here are my other requests, as well as those from my teammates:

4 Likes