Learn Algo Trading with Python | Codes | Youtube Series

@Delta_Trading
Sir Work to kar rha hai
Aap apne code ko check kre

	ce_name, pe_name, ce_strike, pe_strike = tsl.ITM_Strike_Selection(Underlying ='NIFTY', Expiry = 0, ITM_count=1)
	ce_name, pe_name, strike = tsl.ATM_Strike_Selection(Underlying ='NIFTY', Expiry = 0)
	ce_name, pe_name, ce_strike, pe_strike = tsl.OTM_Strike_Selection(Underlying ='NIFTY', Expiry = 0, OTM_count=1)
	ce_name, pe_name, ce_strike, pe_strike = tsl.OTM_Strike_Selection(Underlying ='NIFTY', Expiry = 0, OTM_count=2)

[UPDATE]
@Tradehull_Imran @Dhan Algo successfully deployed on AWS EC2. It auto-triggers at 09:00 IST, runs through the trading session, and terminates gracefully at 16:00.

Solved!!
I was using the older codebase version, now updated to latest one, and the issue is solved.

1 Like

is it possible to fetch customer time frame interval using resampling

yes it is possible..
use below codes

chart = tsl.get_historical_data(tradingsymbol=‘NSE’, exchange=‘INDEX’, timeframe=‘1’)

chart_resmapled = tsl.resample_timeframe(chart, timeframe=‘3’)

1 Like

Hi @ranjith_katta ,

tsl.get_intraday_data was a old method to get historical data.. it gives data only for today, which makes problem if we want to create indicators on it.

Dhanhq was upgraded and now we can use get_historical_data which gives data for last 5 working days.

Retrieve historical or intraday data:

Get Historical Data

  • tsl.get_historical_data(tradingsymbol: str, exchange: str, timeframe: str, debug: str = “NO”)
    • Arguments:
      • tradingsymbol (str): The trading symbol for the instrument you want to fetch data for (e.g., ‘NIFTY’, ‘ACC’).
      • exchange (str): The exchange where the instrument is traded (e.g., ‘NSE’, ‘INDEX’).
      • timeframe (str): The timeframe for the data. It can be:
        • ‘1’ for 1-minute candles
        • ‘5’ for 5-minute candles
        • ‘15’ for 15-minute candles
        • ‘25’ for 25-minute candles
        • ‘60’ for 60-minute candles
        • ‘DAY’ for daily candles
      • debug (optional, str): Set to “YES” to enable detailed API response logging. Default is “NO”.
    • Sample Code:
data = tsl.get_historical_data(tradingsymbol='ACC', exchange='NSE', timeframe="1")

thankyou so much brother it made so much easy for me now

Hi @Delta_Trading , @Bhoopendra_Choudhary ,

Probably you would be using old version of codebase. Run the below code to confirm the version of the codebase:

`pip show Dhan-Tradehull`

The issue is already resolved in the latest codebase. Make sure you are using the latest codebase version.

1 Like

aap usme current sessiion logic dalo try karo aajayega

Is the tradehull workign today? I’m getting the below error.

Exception at getting Expiry list as {'status': 'failure', 'remarks': 'Expecting value: line 1 column 1 (char 0)', 'data': ''}

also, what is the official working Dhan python library? is it 2.0.2 or 2.1 ? Can someone give confirmation?

@Tradehull_Imran

Thanks in advance.

3 Likes

@Sadhanandhan_N
@Dhan
@Tradehull_Imran

Dhan does not provide data on market holidays, they should consider addressing this.

Exception at calling ltp as {'status': 'failure', 'remarks': 'Expecting value: line 1 column 1 (char 0)', 'data': ''}
1 Like

No. it’s unique. I was testing codes every weekend. Never faced this issue. Even Dhanhq (official dhan python library is also throwing error). I think they should address this issue on priority basis. This is really concerning. I reached out to dhan support team also - doesn’t seem like they are concerned about it. @Hardik

1 Like

@Sadhanandhan_N
@Dhan

Dhan should consider it

2 Likes

Same error! has the TradeHull version been updated? Dhan is not able to help.

@Tradehull_Imran
Hi @Tradehull_Imran sir,
kaise hai ap ap ke help se mai ek chota sa algo banaya hai iske liye thank you but sir is me ek error rha hai

  1. ek bar tg or sl hit hone pr same stock ki scanning or reentry pr( ‘NoneType’ object is not subscriptable ) aisa error ata hai to mughe algo retart krna prta hai.

  1. mughe isme ema_21 add krna hai aur buy break candle agar ema ke upar closed ho aur second candle break krne pr buy ho. same iska apposit sell ke liye.
  2. agar previous week ka low ka SL hit or next to next day (2 or # 3days in the week) market reverse ho to 1h ka time pr previous week Low & ema ke upar closed ke second candle pr buy ho ( tg 1:2 & weekly call rahega.

please help & share code proper testing

Error:


Scanning      CIPLA 2025-07-17 12:47:58.276160
'NoneType' object is not subscriptable
Scanning      HCLTECH 2025-07-17 12:48:00.633788
Scanning      HEROMOTOCO 2025-07-17 12:48:02.988629
Scanning      ITC 2025-07-17 12:48:05.346589
Scanning      INDUSINDBK 2025-07-17 12:48:08.742576
Scanning      LT 2025-07-17 12:48:11.029972

code :

import pdb
import time
import datetime
import traceback
from Dhan_Tradehull_V2 import Tradehull
import pandas as pd
import xlwings as xw
from pprint import pprint
import talib
import pandas_ta as ta
import winsound




client_code = "xxxxxx"
token_id    = "xxxxxxxxxxx"
tsl = Tradehull(client_code,token_id)



pre_market_watchlist    = ['ADANIENT', 'ADANIPORTS', 'APOLLOHOSP', 'ASIANPAINT', 'AXISBANK', 'BAJAJ-AUTO', 'BAJFINANCE', 'BAJAJFINSV', 'BEL', 'BHARTIARTL', 'CIPLA', 'COALINDIA', 'DRREDDY', 'EICHERMOT', 'ETERNAL', 'GRASIM', 'HCLTECH', 'HDFCBANK', 'HDFCLIFE', 'HEROMOTOCO', 'HINDALCO', 'HINDUNILVR', 'ICICIBANK', 'ITC', 'INDUSINDBK', 'INFY', 'JSWSTEEL', 'JIOFIN', 'KOTAKBANK', 'LT', 'M&M', 'MARUTI', 'NTPC', 'NESTLEIND', 'ONGC', 'POWERGRID', 'RELIANCE', 'SBILIFE', 'SHRIRAMFIN', 'SBIN', 'SUNPHARMA', 'TCS', 'TATACONSUM', 'TATAMOTORS', 'TATASTEEL', 'TECHM', 'TITAN', 'TRENT', 'ULTRACEMCO', 'WIPRO']
watchlist               = []

for name in pre_market_watchlist:


    print("Pre market scanning ", name)
    day_chart  = tsl.get_historical_data(tradingsymbol = name,exchange = 'NSE',timeframe="DAY")

    # indi = ta.supertrend(day_chart['high'], day_chart['low'], day_chart['close'], 10, 2)   # appy suppertrand
    # day_chart = pd.concat([day_chart, indi], axis=1, join='inner')
    # if day_chart.iloc[-1]['SUPERTd_10_2.0'] == 1:
    #     watchlist.append(name)

    day_chart['upperband'], day_chart['middleband'], day_chart['lowerband'] = talib.BBANDS(day_chart['close'], timeperiod=20, nbdevup=2, nbdevdn=2, matype=0)
    last_dat_candle = day_chart.iloc[-1]

    upper_breakout = last_dat_candle['high'] > last_dat_candle['upperband'] 
    lower_breakout = last_dat_candle['low'] < last_dat_candle['lowerband']


    if upper_breakout or lower_breakout:
        watchlist.append(name)
        print(f"\t selected {name} for trading")
        
        
print(watchlist)
# pdb.set_trace()



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 , 'pyramiding' :None , 'Traling' :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        = "7747163783:AAHV4vxVsAewDmzNDQFcSeCA3b9t8df9-sE"
receiver_chat_id = "5490108905"



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, 20):
        print(f"wait for market to start", current_time)
        time.sleep(1)
        continue

    
    if current_time > datetime.time(15, 15):
        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)
            chart['ema'] = talib.EMA(chart['close'], timeperiod=21)
            indi = ta.supertrend(chart['high'], chart['low'], chart['close'], 7, 3)
            chart = pd.concat([chart, indi], axis=1, join='inner')


            cc  = chart.iloc[-2]

            bc1 = cc['rsi'] > 60
            bc2 = cc['SUPERTd_7_3.0'] == 1
            bc3 = True # cc['ema'] > chart['ema'].iloc[-2]
            bc4 = orderbook[name]['traded'] is None
            # sc1 = cc['rsi'] < 40
            # sc2 = orderbook[name]['traded'] is None


        except Exception as e:
            print(e)
            continue

                

        if bc1 and bc2 and bc3 and bc4:
            print("buy ", name, "\t")
            
            margin_avialable = tsl.get_balance()
            margin_required  = cc['close']/4.8


            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 


            orderbook[name]['name']        = name
            orderbook[name]['date']        = str(current_time.date()) 
            orderbook[name]['entry_time']  = str(current_time.time())[:8]
            orderbook[name]['buy_sell']    = "BUY"
            orderbook[name]['qty']         = 1 #int(10000/close)

            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]['tg']          = round(orderbook[name]['entry_price']*1.002, 1)  # 1.01
                orderbook[name]['sl']          = round(orderbook[name]['entry_price']*0.998, 1)  # 0.99 
                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 cheking")



        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"
                    tg_hit = ltp > orderbook[name]['tg']
                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 = "sl_hit")

                   


                if tg_hit:
                    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']        = round((orderbook[name]['exit_price'] - orderbook[name]['entry_price'])*orderbook[name]['qty'],1) 
                        orderbook[name]['remark']     = "Bought_TG_hit"


                        message = "\n".join(f"'{key}': {repr(value)}" for key, value in orderbook[name].items())
                        message = f"TG_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

                        winsound.Beep(1500, 10000)




                    except Exception as e:
                        print(e)
                        pdb.set_trace(header = "error in sl tg_hit")

@Tradehull_Imran why am I getting following error ?

Dhan_Tradehull_V2.py", line 82, in get_login
print(self.response)
AttributeError: ‘Tradehull’ object has no attribute ‘response’

@Tradehull_Imran @RahulDeshpande HI,
Is there way to download historical data (daily and intraday) for expired futures contracts of Nifty, Gold , Silver etc. ?
How to get the security id of expired instruments ?
Thanks

Hi sir @Tradehull_Imran

I can able to make order placement through coding. Soon will test and upload in the server.

When will you release the tested trailing stop-loss code?

Please make some videos on how to run 2 algos on the server.

do we require Data API token by paying 500 everymonth only then excel will work?

first of all note that 500p.m. is for data fetching and excel if u are taking about in relation to websocket, imran has already told 1000 times that wesocket is difficult to implement so go for historical candle option with xlswriter u can see them in excel