Learn Algo Trading with Python | Codes | Youtube Series

Below is the 'PreMarketScan" file as well

import pdb
import pandas as pd
import time
import warnings,sys

warnings.filterwarnings("ignore")

# ---------------Basic setup for dhan login & Defining Constants------------------------
path = r'C:/Users/krish/OneDrive/Documents/Krishna/2 Areas/Finance/Stock Market/Trading/Trading Courses/Development/AlgoTrading/Dhan/DhanAlgoTrading'
sys.path.insert(0, path)
import credentials as cred
from Dhan_Tradehull_V2 import Tradehull

client_code = cred.CLIENT_ID
token_id = cred.ACCESS_TOKEN
# ---------------------------------------------------------------------------------------

tsl = Tradehull(client_code,token_id)
def premarketscan():
	# pre_market_watchlist = ['INFY', 'M&M', 'HINDALCO', 'TATASTEEL', 'NTPC', 'MARUTI', 'TATAMOTORS', 'ONGC', 'BPCL', 'WIPRO', 'SHRIRAMFIN', 'ADANIPORTS', 'JSWSTEEL', 'COALINDIA', 'ULTRACEMCO', 'BAJAJ-AUTO', 'LT', 'POWERGRID', 'ADANIENT', 'SBIN', 'HCLTECH', 'TCS', 'EICHERMOT', 'BAJAJFINSV', 'TECHM', 'LTIM', 'HINDUNILVR', 'BHARTIARTL', 'AXISBANK', 'GRASIM', 'HEROMOTOCO', 'DRREDDY', 'ICICIBANK', 'HDFCBANK', 'BAJFINANCE', 'SBILIFE', 'RELIANCE', 'KOTAKBANK', 'ITC', 'TITAN', 'SUNPHARMA', 'INDUSINDBK', 'APOLLOHOSP', 'BRITANNIA', 'NESTLEIND', 'HDFCLIFE', 'DIVISLAB', 'CIPLA', 'ASIANPAINT', 'TATACONSUM']
	pre_market_watchlist = ['INFY', 'M&M', 'ONGC', 'BAJAJFINSV' ]

 
	body_dict = {}
	trade_info = {}
	for name in pre_market_watchlist:
		time.sleep(1)
		print(f"Pre market scanning {name}")
		daily_data = tsl.get_historical_data(tradingsymbol = name, exchange = 'NSE',timeframe="DAY")
		ldc = daily_data.iloc[-1]  #last_day_candle
		body_percentage = ((ldc['close'] - ldc['open'])/ldc['open'])*100
		body_dict[name] = round(body_percentage, 2)

	biggest_green_candle = max(body_dict, key=body_dict.get)
	biggest_red_candle = min(body_dict, key=body_dict.get)
	daily_data_green = tsl.get_historical_data(tradingsymbol = biggest_green_candle, exchange = 'NSE',timeframe="DAY")		
	daily_data_red = tsl.get_historical_data(tradingsymbol = biggest_red_candle, exchange = 'NSE',timeframe="DAY")

	ldc_green = daily_data_green.iloc[-1]  #last_day_candle
	ldc_red = daily_data_red.iloc[-1]  #last_day_candle
	
	trade_info["buy"] = {"script": biggest_green_candle,"level": ldc_green['high']}
	trade_info["sell"] = {"script": biggest_red_candle,"level": ldc_red['low']}

 
	trade_info=pd.DataFrame.from_dict(trade_info, orient='index')
	print(trade_info)
	return trade_info

Hi @Priyesh_Sharma

see : Learn Algo Trading with Python | Codes | Youtube Series - #914 by Tradehull_Imran

See video tutorial : https://youtu.be/wlQWSLzp_UI?si=PvnO3cXYs98GQTB5&t=996

Thank you very much , sir…

1 Like

Thank you Sir

1 Like

Sir, first of all, thank you very much for your dedication in teaching a student like me :blush:. I truly appreciate your excellent teaching skills and your prompt responses. The changes implemented by the Dhan team have significantly improved the stability of the algos, resulting in far fewer issues for me.

I am eager to extend my learning to include Fibonacci techniques. Could you please provide some guidance on this topic?

Additionally, I would like to suggest an enhancement for the Dhan app. It would be incredibly helpful if there were a dedicated tab for downloading the complete latest package, including older and stable versions of installations such as Dhan Tradehull files, CSV files, documentation, and example codes. This feature would make it easier for users like me to stay updated and sync more effectively with the platform.

1 Like

Sir, first of all, thank you very much for your dedication in teaching a student like me :blush:. I truly appreciate your excellent teaching skills and your prompt responses. The changes implemented by the Dhan team have significantly improved the stability of the algos, resulting in far fewer issues for me.

I am eager to extend my learning to include Fibonacci techniques. Could you please provide some guidance on this topic?

Additionally, I would like to suggest an enhancement for the Dhan app. It would be incredibly helpful if there were a dedicated tab for downloading the complete latest package, including older and stable versions of installations such as Dhan Tradehull files, CSV files, documentation, and example codes. This feature would make it easier for users like me to stay updated and sync more effectively with the platform. waiting for new series where we can get to more advance learnings :smiling_face:

1 Like

It seems like after Nov 7 release, below method stopped working:
previous_hist_data = tsl.get_historical_data(‘ACC’,‘NSE’,12)
intraday_hist_data = tsl.get_intraday_data(‘ACC’,‘NSE’,1)

Getting below error :

D:\Anand\Trading\Dhanalgo\SessionResources\3. Session3 - Codebase\Dhan codebase>py "Dhan_codebase usage.py"
-----Logged into Dhan-----
reading existing file all_instrument 2024-11-26.csv
Got the instrument file
available_balance 22187.75
[1] > d:\anand\trading\dhanalgo\sessionresources\3. session3 - codebase\dhan codebase\dhan_tradehull.py(223)get_historical_data()
-> df = pd.DataFrame(ohlc['data'])
(Pdb++) print(Symbol,exchangeSegment,instrument_type,str(expiry_code),from_date,to_date)
ACC NSE_EQ EQUITY 0 2024-11-14 2024-11-26
(Pdb++) print(ohlc
*** SyntaxError: unexpected EOF while parsing
(Pdb++) print(ohlc)
{'status': 'failure', 'remarks': "expiry_code value must be ['0','1','2','3']", 'data': ''}
(Pdb++)
{'status': 'failure', 'remarks': "expiry_code value must be ['0','1','2','3']", 'data': ''}

Traceback (most recent call last):
  File "D:\Anand\Trading\Dhanalgo\SessionResources\3. Session3 - Codebase\Dhan codebase\Dhan_Tradehull.py", line 223, in get_historical_data
    df = pd.DataFrame(ohlc['data'])
  File "D:\Anand\Trading\Dhanalgo\SessionResources\3. Session3 - Codebase\Dhan codebase\Dhan_Tradehull.py", line 223, in get_historical_data
    df = pd.DataFrame(ohlc['data'])
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\bdb.py", line 88, in trace_dispatch
    return self.dispatch_line(frame)
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\bdb.py", line 113, in dispatch_line
    if self.quitting: raise BdbQuit
bdb.BdbQuit
intraday_minute_data() missing 2 required positional arguments: 'from_date' and 'to_date'
Traceback (most recent call last):
  File "D:\Anand\Trading\Dhanalgo\SessionResources\3. Session3 - Codebase\Dhan codebase\Dhan_Tradehull.py", line 254, in    ohlc = self.Dhan.intraday_minute_data(str(security_id),exchangeSegment,instrument_type)

hello sir
please help

Hi @kristrades99

I have executed your code, line for atm_ce_ltp seems working fine
atm_ce_ltp = tsl.get_ltp_data(names = [atm_ce_name])[atm_ce_name]

However below code will not work in case of M&M
since you wont get atm_ce_name for M&M, atm_ce_ltp wont be received either
I need to check on this one why is it failing for M&M

atm_ce_name, atm_pe_name, strike = tsl.ATM_Strike_Selection(row['script'],EXPIRY) 
atm_ce_ltp     		= tsl.get_ltp_data(names = [atm_ce_name])[atm_ce_name]

Hi @kristrades99

Also the code is well written :+1:

Hi @aanand1008

These functions have been upgraded get_historical_data and get_intraday_data.

Do use the latest files,

and use dhanhq 2.0.0, send below command on CMD

pip uninstall dhanhq

pip install dhanhq==2.0.0

pip show dhanhq

Hi @vinay_kumaar

1. Do use the latest files Dhan_Tradehull_V2,

2. and use dhanhq 2.0.0, send below command on CMD

pip uninstall dhanhq

pip install dhanhq==2.0.0

pip show dhanhq

Hi @avinashkumar07412
Line no 49 is incorrect, its a pandas code.

do start from here first we can cover the fundamentals

Hi @Tradehull_Imran , Sir.

Upon your teaching and your guidance, I have Completed my Algo, I am getting small errors while exiting the Trade, sir.

Please go through the Algo , and help me , Sir…

My Algo is

import pdb
import time
import datetime
import traceback
from Dhan_Tradehull_V2 import Tradehull
import pandas as pd
from pprint import pprint
import talib
import pandas_ta as pta
import pandas_ta as ta
import warnings
warnings.filterwarnings("ignore")
#-----------------------------------------------------------------------------------
client_code = "11"
token_id    = "11"
tsl = Tradehull(client_code,token_id)
#----------------------------------------------------------------------------------
available_balance = tsl.get_balance()
leveraged_margin  = available_balance*5
max_trades = 20
per_trade_margin = (leveraged_margin/max_trades)
max_loss = available_balance * -0.09				#  max loss of 9%
#-----------------------------------------------------------------------------------------
watchlist = ['GOLDPETAL DEC FUT', 'CRUDEOILM DEC FUT', 'SILVERMIC FEB FUT']
traded_wathclist = []
#-----------------------------------------------------------------------------------------------------
while True:
	live_pnl = tsl.get_live_pnl()
	current_time = datetime.datetime.now().time()

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

	if (current_time > datetime.time(23, 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 see you tomorrow", current_time)
		break

	for stock_name in watchlist:
		time.sleep(2)
		print(f"Scanning {stock_name}")

		# Conditions that are on 1 minute timeframe -------------------------------------------

		chart_1 = tsl.get_historical_data(tradingsymbol=stock_name, exchange='MCX', timeframe="1")
		pervious_candle = chart_1.iloc[-2]
		no_repeat_order  = stock_name not in traded_wathclist

		

		# rsi    ------------------------ apply indicators--------------------------------------
		# Buy when rsi crosses above 55 and sell when rsi crosses below 45

		# Ensure chart_1 has sufficient rows
		if len(chart_1) <= 15:
		    print(f"Not enough data for {stock_name}. Skipping.")
		    continue

		# Calculate RSI and drop NaN values
		chart_1['rsi'] = talib.RSI(chart_1['close'], timeperiod=14)
		chart_1['prev_rsi'] = chart_1['rsi'].shift(1)
		chart_1.dropna(subset=['rsi', 'prev_rsi'], inplace=True)

		# Add crossover columns
		chart_1['uptrend_cross'] = (chart_1['prev_rsi'] <= 55) & (chart_1['rsi'] > 55)
		chart_1['downtrend_cross'] = (chart_1['prev_rsi'] >= 45) & (chart_1['rsi'] < 45)

		# Ensure the columns exist in the completed candle
		cc_1 = chart_1.iloc[-2]  # Second-to-last row
		if 'uptrend_cross' not in cc_1 or 'downtrend_cross' not in cc_1:
		    print(f"Missing crossover columns for {stock_name}. Skipping.")
		    continue

		# Access crossover values
		uptrend_1 = cc_1['uptrend_cross']
		downtrend_1 = cc_1['downtrend_cross']
		print(f"Uptrend: {uptrend_1}, Downtrend: {downtrend_1}")



		# Supertrend for Exit from open position -------------------------- apply indicators-----------------------------------
		indi 			= ta.supertrend(chart_1['high'], chart_1['low'], chart_1['close'], 10, 1)
		chart_1 		= pd.concat([chart_1, indi], axis=1, join='inner')
		cc_1            = chart_1.iloc[-2]  #pandas  completed candle of 1 min timeframe
		exit_sell 		= cc_1['close'] > cc_1['SUPERT_10_1.0']
		exit_buy	 	= cc_1['close'] < cc_1['SUPERT_10_1.0']

		



		# BUY conditions ------------------------------------------------------------------------------
		 
		breakout_b1 = ((pervious_candle['close'] - pervious_candle['open']) / pervious_candle['open']) * 100  # percentage change
		breakout_b2 = pervious_candle['volume'] > 0.2 * chart_1['volume'].mean()
		
		
		if uptrend_1 and breakout_b2 and (0.01 <= breakout_b1 <= 0.4) and no_repeat_order:

			print(stock_name, "is in uptrend, Buy this script")

			lot_size = tsl.get_lot_size(stock_name)

			# Place buy order-------------------------------------------------------------------------
			entry_orderid = tsl.order_placement(stock_name, 'MCX', lot_size, 0, 0, 'MARKET', 'BUY', 'MIS')
			traded_wathclist.append(stock_name)
			

		# SELL conditions -----------------------------------------------------------------------------
		 
		breakout_s1 = ((pervious_candle['close'] - pervious_candle['open']) / pervious_candle['open']) * 100  # percentage change
		breakout_s2 = pervious_candle['volume'] > 0.2 * chart_1['volume'].mean()


		if downtrend_1 and breakout_s2 and (-0.4 <= breakout_s1 <= -0.01) and no_repeat_order:

			print(stock_name, "is in downtrend, Sell this script")
			lot_size = tsl.get_lot_size(stock_name)		

			# Place sell order-------------------------------------------------------------------------

			entry_orderid 	   = tsl.order_placement(stock_name, 'MCX', lot_size, 0, 0, 'MARKET', 'SELL', 'MIS')
			traded_wathclist.append(stock_name)

			
		# Exit conditions based on Supertrend indicator----------------------------------------------------

	for stock_name in traded_wathclist:
	    time.sleep(2)
	    print(f"Checking exit conditions for {stock_name}")

	    # Fetch updated 1-minute chart
	    chart_1 = tsl.get_historical_data(tradingsymbol=stock_name, exchange='MCX', timeframe="1")
	    
	    # Apply Supertrend indicator again
	    indi = ta.supertrend(chart_1['high'], chart_1['low'], chart_1['close'], 10, 1)
	    chart_1 = pd.concat([chart_1, indi], axis=1, join='inner')
	    cc_1 = chart_1.iloc[-2]  # Get the completed candle

	    # Exit conditions
	    exit_sell = cc_1['close'] > cc_1['SUPERT_10_1.0']
	    exit_buy = cc_1['close'] < cc_1['SUPERT_10_1.0']

	    # Check for existing positions to square off
	    position = tsl.get_position(stock_name)  # Get current position details
	    
	    if position['type'] == 'BUY' and exit_buy:
	        print(f"Exiting BUY position for {stock_name}")
	        exit_orderid = tsl.order_placement(stock_name, 'MCX', position['lot_size'], 0, 0, 'MARKET', 'SELL', 'MIS')
	        traded_wathclist.remove(stock_name)

	    elif position['type'] == 'SELL' and exit_sell:
	        print(f"Exiting SELL position for {stock_name}")
	        exit_orderid = tsl.order_placement(stock_name, 'MCX', position['lot_size'], 0, 0, 'MARKET', 'BUY', 'MIS')
	        traded_wathclist.remove(stock_name)

My error message is

GOLDPETAL DEC FUT is in uptrend, Buy this script
Checking exit conditions for GOLDPETAL DEC FUT
Traceback (most recent call last):
  File "MCX - Exit.py", line 147, in <module>
    position = tsl.get_position(stock_name)  # Get current position details
AttributeError: 'Tradehull' object has no attribute 'get_position'

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

Solve

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

Solve

Hi @Abhishek_Konda @aanand1008 @francis_antony @avinashkumar07412 @kristrades99 @vinay_kumaar @Priyesh_Sharma @Samis @himansshu_joshi @everyone

Solve

Frankly Speaking , after reading those codes , I am sure that I can't give answer in Code :hugs:

I think only experts can give Answer by code…

But I can conclude/My answer would be :- Build Live Algo in YOUTUBE with Q&A Implementation :melting_face:

This is my answer, Sir. :slightly_smiling_face:

1 Like

@Tradehull_Imran

BUILD ALGO LIVE

1 Like

Same Error getting
DataFrame constructor not properly called!
Traceback (most recent call last):
File “/Users/parveenchugh/python/3. Session3 - Codebase/Dhan codebase/Dhan_Tradehull.py”, line 222, in get_historical_data
df = pd.DataFrame(ohlc[‘data’])
File “/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/site-packages/pandas/core/frame.py”, line 887, in init
raise ValueError(“DataFrame constructor not properly called!”)
ValueError: DataFrame constructor not properly called!