@Tradehull_Imran please can you upload the .py files used in Session 6 money management and Session 7 options call buying. Kudos to you and Dhan team for this extremely impactful series, one of the best series I have come across in YouTube. Thankful to you for the knowledge sharing!
Hi, i was facing same issue. I guess on non working days/weekends, the “tsl.get_ltp_data(names = watchlist)” does not return any values for LTP. For running the scripts on non working days, I had to manually hard code values of ltp with last closed candle[‘high’].max() value for the test run.
I agree
hello sir do you please share me code file number 6 and 7 ?
Updated in the main post! Check it out.
@RahulDeshpande thank you. Since the files are uploaded till session 11, might as well upload the YouTube videos as well. I understand the videos were recorded in December-2024.
Youtube videos are being edited as we speak - we upload it once it gets done. But we are at it - should be over by end of march.
@ Tradehull_Imran, sir
@ RahulDeshpande sir
I am currently experiencing an issue with my Data API subscription:
- Active Subscription:** I have an active Data API subscription with approximately 6 hours remaining.
- Unsubscription Attempt:** I attempted to unsubscribe and resubscribe to resolve the issue. However, the system does not permit re-subscription until the current subscription expires.
- Sufficient Funds:
There are adequate funds in both my Dhan account and linked UPI account for auto-renewal. Despite this, the renewal process appears to be stuck. Your guidance on how to proceed would be helpful.
Sir, after completion of trade when the code reads through the excel again. it is showing as object type in not subscriptable. How do we solve this?
Dear Imran sir, can you please arrange a small clip on how to get alerts in telegram, while using your codes in advanced algo sir.
I do have telegram app in my mobile, but have no idea on how to link it to get alerts.
Please sir.
VBR Prasad
@Tradehull_Imran , how to get_historical_data for a period?
@Tradehull_Imran
Sir, when I run my algo today, I got this error. Why did this error occur?
-----Logged into Dhan-----
reading existing file all_instrument 2025-04-01.csv
Got the instrument file
{‘status’: ‘failure’, ‘remarks’: ‘HTTPSConnectionPool(host='api.dhan.co', port=443): Max retries exceeded with url: /v2/charts/intraday (Caused by NameResolutionError(“<urllib3.connection.HTTPSConnection object at 0x0000018EDCA72610>: Failed to resolve 'api.dhan.co' ([Errno 11001] getaddrinfo failed)”))’, ‘data’: ‘’}
Traceback (most recent call last):
File “D:\Python\00. 01 Final\Dhan_Tradehull_V2.py”, line 563, in get_intraday_data
raise Exception(ohlc)
Exception: {‘status’: ‘failure’, ‘remarks’: ‘HTTPSConnectionPool(host='api.dhan.co', port=443): Max retries exceeded with url: /v2/charts/intraday (Caused by NameResolutionError(“<urllib3.connection.HTTPSConnection object at 0x0000018EDCA72610>: Failed to resolve 'api.dhan.co' ([Errno 11001] getaddrinfo failed)”))’, ‘data’: ‘’}
Nifty chart data is empty or unavailable. Skipping processing.
Error occurred: object of type ‘NoneType’ has no len(). Skipping processing.
Hi @Tradehull_Imran ,
I am running below code for getting combined vwap for ATM getting below error.
import pandas_ta as pta
def get_vwap_data(atm_call_name, atm_put_name):
atm_ce_index_chart = tsl.get_historical_data(tradingsymbol = atm_call_name, exchange = 'NFO', timeframe = "1")
atm_ce_index_chart.set_index(pd.DatetimeIndex(atm_ce_index_chart['timestamp']), inplace = True)
atm_ce_index_chart['vwap'] = pta.vwap(atm_ce_index_chart['high'], atm_ce_index_chart['low'],
atm_ce_index_chart['close'], atm_ce_index_chart['volume'])
atm_pe_index_chart = tsl.get_historical_data(tradingsymbol = atm_put_name, exchange = 'NFO', timeframe = "1")
atm_pe_index_chart['vwap'] = pta.vwap(atm_pe_index_chart['high'], atm_pe_index_chart['low'],
atm_pe_index_chart['close'], atm_pe_index_chart['volume'])
combined_premium_vwap = atm_ce_index_chart['vwap'] + atm_pe_index_chart['vwap']
return combined_premium_vwap
Getting below error.
Scanning NIFTY 2025-04-01 09:36:13.918703
C:/Dhan/New APP/Session 7/Options Selling vwap Algo.py:47: UserWarning: Converting to PeriodArray/Index representation will drop timezone information.
atm_ce_index_chart['vwap'] = pta.vwap(atm_ce_index_chart['high'], atm_ce_index_chart['low'],
[!] VWAP volume series is not datetime ordered. Results may not be as expected.
[!] VWAP price series is not datetime ordered. Results may not be as expected.
'RangeIndex' object has no attribute 'to_period'
starting while Loop
@Tradehull_Imran dear please check my code for trailing stoploss
Adjust SL Based on Trade Type
if trade[“type”] == “BUY”:
new_trailing_sl = last_price - sl_points # SL moves UP for LONG trades
if new_trailing_sl > old_sl: # Ensure SL moves in the right direction
try:
tsl.modify_order(order_id=trade[‘sl_order_id’],stop_loss=new_trailing_sl)
trade[“sl”] = new_trailing_sl
print(f" Updated SL for {stock_name}: {old_sl} → {new_trailing_sl}")
@Tradehull_Imran
I was changed code from option buying to equity buying.
please check code is correct or not
please.
import pdb
import time
import datetime
import traceback
from Dhan_Tradehull import Tradehull
import pandas as pd
from pprint import pprint
import talib
import pandas_ta as ta
import xlwings as xw
import winsound
import sqn_lib
client_code = “1000728206”
token_id = “eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJkaGFuIiwicGFydG5lcklkIjoiIiwiZXhwIjoxNzQ1Mzg1MjQyLCJ0b2tlbkNvbnN1bWVyVHlwZSI6IlNFTEYiLCJ3ZWJob29rVXJsIjoiIiwiZGhhbkNsaWVudElkIjoiMTAwMDcyODIwNiJ9.e10wS0hlk9DwEFw-MHH_FxFhmO_I7C05RDxhXgGcEpN2a8OpwyUGWcSZxmi3Q-CxTUOscaBTaPkQNfxzlxtwEA”
tsl = Tradehull(client_code,token_id)
opening_balance = tsl.get_balance()
base_capital = 1579.74
market_money = opening_balance - base_capital
beacuse I am loosing money, so I have 0 market money, and I can take risk on the current opening balance and not on the base capital
if (market_money < 0):
market_money = 0
base_capital = opening_balance
market_money_risk = (market_money1)/100
base_capital_risk = (base_capital0.5)/100
max_risk_for_today = base_capital_risk + market_money_risk
max_order_for_today = 2
risk_per_trade = (max_risk_for_today/max_order_for_today)
atr_multipler = 3
risk_reward = 3
watchlist = [‘TATACONSUM’,‘KOTAKBANK’,‘APOLLOHOSP’,‘ONGC’,‘ICICIBANK’,‘TATAMOTORS’,‘HINDUNILVR’,‘JIOFIN’,‘SBILIFE’,‘HDFCLIFE’,‘AXISBANK’,‘BEL’,‘NESTLEIND’,‘ITC’,‘BHARTIARTL’,‘SUNPHARMA’,‘COALINDIA’,‘JSWSTEEL’,‘HDFCBANK’,‘EICHERMOT’,‘SBIN’,‘BAJAJFINSV’,‘RELIANCE’,‘LT’,‘GRASIM’,‘ASIANPAINT’,‘TECHM’,‘NTPC’,‘BAJFINANCE’,‘TITAN’,‘TATASTEEL’,‘ULTRACEMCO’,‘TCS’,‘HEROMOTOCO’,‘ADANIPORTS’,‘BAJAJ-AUTO’,‘DRREDDY’,‘HINDALCO’,‘POWERGRID’,‘MARUTI’,‘ADANIENT’,‘TRENT’,‘INFY’,‘HCLTECH’,‘ZOMATO’,‘M&M’,‘CIPLA’,‘SHRIRAMFIN’,‘WIPRO’,‘INDUSINDBK’]
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 = {}
wb = xw.Book(‘Live Trade Data.xlsx’)
live_Trading = wb.sheets[‘Live_Trading’]
completed_orders_sheet = wb.sheets[‘completed_orders’]
reentry = “yes” #“yes/no”
completed_orders =
bot_token = “7746461948:AAHR7MQSe40UA9jMZuw7-u2XhvBpwwR1ozQ”
receiver_chat_id = “1570007384”
live_Trading.range(“A2:Z100”).value = None
completed_orders_sheet.range(“A2:Z100”).value = None
for name in watchlist:
orderbook[name] = single_order.copy()
while True:
print("starting while Loop \n\n")
current_time = datetime.datetime.now().time()
if current_time < datetime.time(9, 15):
print(f"Wait for market to start", current_time)
time.sleep(1)
continue
live_pnl = tsl.get_live_pnl()
max_loss_hit = live_pnl < (max_risk_for_today*-1)
market_over = current_time > datetime.time(15, 15)
if max_loss_hit or market_over:
order_details = tsl.cancel_all_orders()
print(f"Market over Closing all trades !! Bye Bye See you Tomorrow", current_time)
pdb.set_trace()
break
all_ltp = tsl.get_ltp_data(names = watchlist)
for name in watchlist:
orderbook_df = pd.DataFrame(orderbook).T
live_Trading.range('A1').value = orderbook_df
completed_orders_df = pd.DataFrame(completed_orders)
completed_orders_sheet.range('A1').value = completed_orders_df
current_time = datetime.datetime.now()
print(f"Scanning {name} {current_time}")
try:
chart = tsl.get_historical_data(tradingsymbol = name,exchange = 'NSE',timeframe="5")
chart['rsi'] = talib.RSI(chart['close'], timeperiod=14)
indi = ta.supertrend(chart['high'], chart['low'], chart['close'], 7, 3)
chart = pd.concat([chart, indi], axis=1, join='inner')
sqn_lib.sqn(df=chart, period=21)
chart['market_type'] = chart['sqn'].apply(sqn_lib.market_type)
chart['atr'] = talib.ATR(chart['high'], chart['low'], chart['close'], timeperiod=14)
cc = chart.iloc[-2]
no_of_orders_placed = orderbook_df[orderbook_df['qty'] > 0].shape[0] + completed_orders_df[completed_orders_df['qty'] > 0].shape[0]
# buy entry conditions
bc1 = cc['rsi'] > 1
bc2 = cc['SUPERTd_7_3.0'] == 1
bc3 = cc['market_type'] != "neutral"
bc4 = no_of_orders_placed < 5
bc5 = orderbook[name]['traded'] is None
except Exception as e:
print(e)
continue
if bc1 and bc2 and bc3 and bc4 and bc5:
print("buy ", name, "\t")
margin_avialable = tsl.get_balance()
margin_required = cc['close']/4.5
if margin_avialable < margin_required:
print(f"Less margin, not taking order : margin_avialable is {margin_avialable} and margin_required is {margin_required} for {name}")
continue
# ce_name, pe_name, ce_otm_strike, pe_otm_strike = tsl.OTM_Strike_Selection(Underlying='NIFTY', Expiry=0, OTM_count=2)
# lot_size = tsl.get_lot_size(tradingsymbol = ce_name)
# options_chart = tsl.get_historical_data(tradingsymbol = ce_name,exchange = 'NFO',timeframe="5")
# options_chart['atr'] = talib.ATR(options_chart['high'], options_chart['low'], options_chart['close'], timeperiod=14)
rc_chart = chart.iloc[-1]
orderbook[name]['name'] = name
# orderbook[name]['options_name'] = ce_name
orderbook[name]['date'] = str(current_time.date())
orderbook[name]['entry_time'] = str(current_time.time())[:8]
orderbook[name]['max_holding_time'] = datetime.datetime.now() + datetime.timedelta(hours=2)
orderbook[name]['buy_sell'] = "BUY"
sl_points = rc_chart['atr']*atr_multipler
orderbook[name]['qty'] = int(int((risk_per_trade*0.7)/sl_points))
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]['sl'] = round(orderbook[name]['entry_price'] - sl_points, 1) # 99
orderbook[name]['tsl'] = orderbook[name]['sl']
price = orderbook[name]['sl'] - 0.05
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"
message = "\n".join(f"'{key}': {repr(value)}" for key, value in orderbook[name].items())
message = f"Entry_done {name} \n\n {message}"
tsl.send_telegram_alert(message=message,receiver_chat_id=receiver_chat_id,bot_token=bot_token)
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"
holding_time_exceeded = datetime.datetime.now() > orderbook[name]['max_holding_time']
current_pnl = round((ltp - orderbook[name]['entry_price'])*orderbook[name]['qty'],1)
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"
message = "\n".join(f"'{key}': {repr(value)}" for key, value in orderbook[name].items())
message = f"SL_HIT {name} \n\n {message}"
tsl.send_telegram_alert(message=message,receiver_chat_id=receiver_chat_id,bot_token=bot_token)
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 holding_time_exceeded and (current_pnl < 0):
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'] = "holding_time_exceeded_and_I_am_still_facing_loss"
message = "\n".join(f"'{key}': {repr(value)}" for key, value in orderbook[name].items())
message = f"holding_time_exceeded_and_I_am_still_facing_loss {name} \n\n {message}"
tsl.send_telegram_alert(message=message,receiver_chat_id=receiver_chat_id,bot_token=bot_token)
if reentry == "yes":
completed_orders.append(orderbook[name])
orderbook[name] = None
winsound.Beep(1500, 10000)
except Exception as e:
print(e)
pdb.set_trace(header = "error in tg_hit") # Testing changes. sadhasd ajsdas dbna sdb abs da sd asd abs d asd
chart_name = orderbook[name]['name']
chart = tsl.get_historical_data(tradingsymbol = chart_name,exchange = 'NSE',timeframe="5")
chart['atr'] = talib.ATR(chart_name['high'], chart_name['low'], chart_name['close'], timeperiod=14)
rc_chart = chart.iloc[-1]
sl_points = rc_chart['atr']*atr_multipler
chart_ltp = tsl.get_ltp_data(names = chart_name)[chart_name]
tsl_level = chart_ltp - sl_points
if tsl_level > orderbook[name]['tsl']:
trigger_price = round(tsl_level, 1)
price = trigger_price - 0.05
tsl.modify_order(order_id=orderbook[name]['sl_orderid'],order_type="STOPLIMIT",quantity=25,price=price,trigger_price=trigger_price)
orderbook[name]['tsl'] = tsl_level
# order_ids = tsl.place_slice_order(tradingsymbol=“NIFTY 19 DEC 24400 CALL”, exchange=“NFO”,quantity=10000, transaction_type=“BUY”,order_type=“LIMIT”,trade_type=“MIS”,price=0.05)
The session 7 had part 2 so the post over here that says session 8 is the part 2 or actually the session 8. It will be good if you add the youtube link of the view along with the drive link for easy understanding.
@Tradehull_Imran @Dhan @RahulDeshpande
I saw your video about Episode 9: Replaying Option Chain.
However, when I tried to run the code for previous expiries it was not showing any output.
After debugging I found that instruments file was not containing any records for historical option chain.
How can we backtest or replay historic option chain.
Please assist me on this.
@Tradehull_Imran @RahulDeshpande sirs,
@Tradehull_Imran @RahulDeshpande Sirs,
Your patience and continuous support are truly admirable. Pls hold our hand few more days…I believe our batch is now very close to breaking through the wall of failures and entering a phase of consistently profitable trades. We just need your guidance for at least one more month to get there.
I’m currently testing one option Greeks-based strategy that sometimes requires placing orders almost every second—or 10 to 13 orders within 1-minute and 5-minute timeframes. I’m managing this with time.sleep intervals, but that sometimes leads to missed entries, especially at key Fibonacci levels.
I know you’ve already provided such logic in some of your codes, but I’m trying to implement it specifically on Nifty options and facing a few issues with the existing code functions.
Could you please let me know the maximum number of orders I can place within 1 minute, 5 minutes, and 15 minutes? ( Including entry order,sl modify order and target order)
Also, if you have a sample code for nifty options:
- order placement,
- order monitoring,
- fixed target & fixed stop-loss,
- executing one trade at a time and then taking the next trade only after the previous one completes,
…it would be of great help. I feel I’m very close to deploying my first algo strategy.
If you’re unable to share this publicly, I’d be grateful to connect personally. Kindly share your contact number if you’re comfortable.
Thank you again for everything!
Hi @Tradehull_Imran and @Dhan team, This entire Algo Trading series (both 1&2) have been amazing. The way it has been packaged and delivered has accelerated my Algo Trading journey for sure. A big thank you from the bottom of my heart. Looking forward to Series - 3 on “Backtesting” so that we are able to sharpen our algos and become better traders.
Kudos to all of you!!