Learn Algo Trading with Python | Codes | Youtube Series

Good mornig @Tradehull_Imran Sir
weekly candle ka high low close ke liye kya code de…
please help

Hi @Arun_Rawat

The behavior after enabling or disabling is correct.

Do remove

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

and use below code to manage exceptions


	try:
		index_chart = tsl.get_historical_data(tradingsymbol = 'NIFTY JAN FUT',exchange = 'NFO',timeframe="1")
	except Exception as e:
		print(e)
		continue


Hi @Pradeep_chaurasiya

rename the file from Dhan_codebase usage to Dhan_codebase_usage (we have removed spacebar and added underscore)

now if you run py Dhan_codebase_usage.py the file will run.

mostly the cmd is taking incomplete filename thus causing the issue

@Tradehull_Imran

watchlist = ['NIFTY 02 JAN 22500 CE', 'NIFTY 02 JAN 22500 PE', 'NIFTY 02 JAN 22550 CE']
traded_wathclist = []
while True:
	time.sleep(0.2)
	for strike_price in watchlist:
		LTP_DATA= tsl.get_historical_data(tradingsymbol = strike_price,exchange = 'NFO',timeframe="1")
		print (strike_price,"-" ,LTP_DATA)
		pdb.set_trace()

Can you please rectify this code

Codebase Version 2.1
-----Logged into Dhan-----
reading existing file all_instrument 2024-12-31.csv
Got the instrument file
Exception in Getting OHLC data as single positional indexer is out-of-bounds
NIFTY 02 JAN 22500 CE - None
[0] > e:\main_algo_trading\8. session8- 2nd live algo\8. session8- 2nd live algo\8. session 8 dhan_tradehull_v2\option data.py(29)<module>()
-> for strike_price in watchlist:
(Pdb++)

Hi @praveen_kumar_kaka1

we don’t need to use historical data to calculate top gainers or losers.
we can call quote data for all 225 scripts in 1 second and then calculate them

use below code

watchlist = ['CESC', 'ATUL', 'HUDCO', 'SIEMENS', 'GNFC', 'INDUSTOWER', 'KEI', 'ICICIGI', 'ATGL', 'DALBHARAT', 'ZYDUSLIFE', 'OBEROIRLTY', 'PFC', 'ITC', 'ADANIPORTS', 'TATACHEM', 'AUROPHARMA', 'TVSMOTOR', 'MUTHOOTFIN', 'AMBUJACEM', 'BALKRISIND', 'INDIANB', 'MGL', 'PRESTIGE', 'IGL', 'PETRONET', 'HINDCOPPER', 'POLYCAB', 'BANKINDIA', 'HINDALCO', 'DABUR', 'NAVINFLUOR', 'SYNGENE', 'AARTIIND', 'ABB', 'ABBOTINDIA', 'ALKEM', 'ASTRAL', 'BHEL', 'COALINDIA', 'CONCOR', 'CUMMINSIND', 'GLENMARK', 'GODREJCP', 'HAL', 'HINDPETRO', 'INDIAMART', 'JKCEMENT', 'LAURUSLABS', 'LTTS', 'METROPOLIS', 'MFSL', 'ONGC', 'PEL', 'SAIL', 'SRF', 'TATACOMM', 'TATAMOTORS', 'UBL', 'BSE', 'IEX', 'NHPC', 'TATASTEEL', 'TRENT', 'RAMCOCEM', 'HDFCLIFE', 'HFCL', 'NMDC', 'PIDILITIND', 'CHAMBLFERT', 'LUPIN', 'TATAPOWER', 'IOC', 'POWERGRID', 'INDIGO', 'BRITANNIA', 'KPITTECH', 'NYKAA', 'BHARATFORG', 'CAMS', 'JSWSTEEL', 'SJVN', 'BAJAJ-AUTO', 'APOLLOHOSP', 'HAVELLS', 'IPCALAB', 'MRF', 'OIL', 'BEL', 'IRCTC', 'LICHSGFIN', 'HINDUNILVR', 'MANAPPURAM', 'VEDL', 'ABCAPITAL', 'MARICO', 'TIINDIA', 'ULTRACEMCO', 'BERGEPAINT', 'SBIN', 'PVRINOX', 'RECLTD', 'ESCORTS', 'YESBANK', 'GAIL', 'BOSCHLTD', 'CYIENT', 'LTF', 'RELIANCE', 'TORNTPHARM', 'CIPLA', 'IRB', 'NESTLEIND', 'TITAN', 'GRANULES', 'BHARTIARTL', 'BSOFT', 'DIVISLAB', 'IDEA', 'BAJFINANCE', 'DELHIVERY', 'LICI', 'CDSL', 'M&M', 'NCC', 'SUPREMEIND', 'TATAELXSI', 'UNITDSPR', 'ABFRL', 'SBILIFE', 'EXIDEIND', 'SBICARD', 'BANDHANBNK', 'MARUTI', 'SHREECEM', 'KOTAKBANK', 'CUB', 'GMRAIRPORT', 'ASIANPAINT', 'COLPAL', 'PIIND', 'SONACOMS', 'SUNPHARMA', 'CANBK', 'NTPC', 'BANKBARODA', 'NATIONALUM', 'LTIM', 'ACC', 'BAJAJFINSV', 'HDFCBANK', 'ADANIGREEN', 'DEEPAKNTR', 'KALYANKJIL', 'LT', 'DRREDDY', 'ICICIPRULI', 'APOLLOTYRE', 'COROMANDEL', 'IDFCFIRSTB', 'TATACONSUM', 'POONAWALLA', 'BIOCON', 'JSWENERGY', 'MOTHERSON', 'PAGEIND', 'GRASIM', 'DIXON', 'INDUSINDBK', 'TCS', 'PAYTM', 'EICHERMOT', 'RBLBANK', 'CROMPTON', 'HEROMOTOCO', 'ICICIBANK', 'ASHOKLEY', 'BPCL', 'LALPATHLAB', 'MCX', 'SUNTV', 'OFSS', 'CGPOWER', 'ADANIENT', 'TECHM', 'MPHASIS', 'APLAPOLLO', 'HCLTECH', 'GODREJPROP', 'INFY', 'JUBLFOOD', 'M&MFIN', 'SHRIRAMFIN', 'AXISBANK', 'JINDALSTEL', 'UPL', 'PNB', 'JIOFIN', 'UNIONBANK', 'ANGELONE', 'HDFCAMC', 'VBL', 'JSL', 'WIPRO', 'DMART', 'ADANIENSOL', 'INDHOTEL', 'BATAINDIA', 'CHOLAFIN', 'CANFINHOME', 'COFORGE', 'NAUKRI', 'DLF', 'ZOMATO', 'MAXHEALTH', 'LODHA', 'VOLTAS', 'IRFC', 'GUJGASLTD', 'PERSISTENT', 'FEDERALBNK', 'AUBANK', 'POLICYBZR']


quote_data = tsl.get_quote(names = watchlist)
quote_data = pd.DataFrame(quote_data).T
quote_data['change_pct'] = (quote_data['net_change']/quote_data['last_price'])*100


top_gaines  = quote_data['change_pct'].sort_values(ascending=False).head(5).index.to_list()
top_loosers = quote_data['change_pct'].sort_values(ascending=False).tail(5).index.to_list()


# output : 
#     top_gaines  ... ['HUDCO', 'KOTAKBANK', 'MUTHOOTFIN', 'LUPIN', 'BEL']
# 	top_loosers ... ['INDHOTEL', 'ATGL', 'PERSISTENT', 'LODHA', 'ADANIGREEN']

2 Likes

@Tradehull_Imran Sir Can you please tell error in this code?

Hi @vinay_kumaar

use below code , for weekly and monthly candles

chart_daily = tsl.get_historical_data(tradingsymbol="ACC", exchange='NSE', timeframe="DAY")

chart_daily['timestamp'] = pd.to_datetime(chart_daily['timestamp'])
chart_weekly = chart_daily.set_index('timestamp').resample('W-MON', closed='left', label='left').agg({'open':'first', 'high':'max', 'low':'min', 'close':'last', 'volume':'sum'}).dropna()
chart_monthly = chart_daily.set_index('timestamp').resample('MS', closed='left', label='left').agg({'open':'first', 'high':'max', 'low':'min', 'close':'last', 'volume':'sum'}).dropna()

1 Like

Hi @Priyanshu_Chhoker

The watchlist has typo for wrong script names,

wrong : NIFTY 02 JAN 22500 CE
correct : NIFTY 02 JAN 22500 CALL

do modify the watchlist,

Also for correct names of script you can refer Dhan console.

2 Likes

Never risk more than you can afford to lose, and always aim for a reward that justifies the risk.

Backtested for Risk-Reward variations vs Cumulative Pnl.

2 Likes

Sir,
मैंने Dhan_codebase usage और Dhan_websocket फाईल में अपना token_id & access_token अपडेट कर Dhan_codebase usage फाईल को Run किया पहले तो excel की फाईल Open हो गई। फिर Dhan_websocket फाईल को Run किया पर excel में Data Update नहीं हो रहा है। (इस प्रोसेस को मैंने Market hours में किया है।)

सर,
कृपया मार्गदर्शन करें।

Hi @Anil_Dhruw

Solution link : Learn Algo Trading with Python | Codes | Youtube Series - #952 by Tradehull_Imran

if traded == "yes":

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


		if long_position:
			sl_hit = index_ltp < trade_info['sl']
			tg_hit = index_ltp < running_candle['SUPERT_10_2.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')


		if short_position:
			sl_hit = index_ltp > trade_info['sl']
			tg_hit = index_ltp > running_candle['SUPERT_10_2.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')
				

Sir, how to maintain RRR in this code? I want to pul SL 15 points and the target is 30 Points or (in percentage also)? Thanks

Hi @Tradehull_Imran ,

I am not able to fetch historical data

*DataFrame constructor not properly called!*
*Traceback (most recent call last):*
*  File "D:\Desktop\dhanApi\fromDhan\3. Session3 - Codebase\3. Session3 - Codebase\3. Session3 - Codebase\Dhan codebase\Dhan_Tradehull.py", line 222, in get_historical_data*
*    df = pd.DataFrame(ohlc['data'])*
*  File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\frame.py", line 817, in __init__*
*    raise ValueError("DataFrame constructor not properly called!")*
*ValueError: DataFrame constructor not properly called!*

Getting the following error

@Tradehull_Imran Please help in this regarding. Do I need to change in the Tradehull file?

Also is there any need to buy data API for now?

Yes , need to subscription for historical data

1 Like

Wow, wonderful Quote, sir… :saluting_face: :slightly_smiling_face:

Great Strategy, Sir, Giving R:R 8:1 … :star_struck:

Whether all these has been covered in Advance Algo You Tube Series ( How to BackTest Algo )???

is this resolved yet ?

Hi @Tradehull_Imran sir,
Happy new year

What I want to say hope you already considered that

In Dhan HQ API as we have
Option chain
Volume
20 depth Ask and Bid

So we can take easily one more near accurate steps with considering ask bid spread
Besides long / short build up, volume, Highest Open interest.

Please let me know your views, our respected @Tradehull_Imran sir🙏

1 Like

@Tradehull_Imran

how do i filter and avoid stocks in scan which does not have margin available.
here i can not use leverage margin as it has 1X only.

available_balance = tsl.get_balance()

leveraged_margin = available_balance*1

max_trades = 4

per_trade_margin = (leveraged_margin/max_trades)

traded_wathclist = # this will cover traded stocks

Very Good Morning Imran Ali Sir, Wish you and your family a very happy New Year 2025, with long and blessed life of Hundred Years, with all Happiness, Good Health, Peace Prosperity and Joyful life sir. Please extend my New Year wishes to all the Forum Members of MADE FOR TRADE. VBR Prasad

1 Like