Learn Algo Trading with Python | Codes | Youtube Series

Hi Imran sir can i have advance algo series code link,

During Testing algo part 1 and 2

I can’t see Advance algo series codes anywhere,

While testing there was multiple error can i have that code,

For study purpose want to understand what my bot expect to be return for every execution,

Example
If my entry failed,

Bot gives multiple error, bot expect sl order id, price Traded status

Hi imran sir, I have leartn a lot from your algo series. Seroiously it is best on internet. I was looking for data to learn algo past 2-3 months but no hope. But form your series only i am able to create a small algo for me. Only problem is that it runs on 5 minute candleframe via tsl.get_historical_data but i want it for 3 minute and i tried your other method defined in tradehull_v2 which is

chart_3 = tsl.get_intraday_data(tradingsymbol=“NIFTY”, exchange=“NFO”, timeframe=“3”, debug=“NO”)

but evertytime it gives error

{‘status’: ‘failure’, ‘remarks’: {‘error_code’: ‘DH-905’, ‘error_type’: ‘Input_Exception’, ‘error_message’: ‘System is unable to fetch data due to incorrect parameters or no data present’}, ‘data’: {‘errorType’: ‘Input_Exception’, ‘errorCode’: ‘DH-905’, ‘errorMessage’: ‘System is unable to fetch data due to incorrect parameters or no data present’}}
Traceback (most recent call last):
File “e:\Python\DHAN\Algos\Dhan_Tradehull_V2.py”, line 569, in get_intraday_data le to fetch data due to incorrect parameters or no data present’}, ‘data’: {‘errorType’: ‘Input_Exception’, ‘errorCode’: ‘DH-905’,
Exception: {‘status’: ‘failure’, ‘remarks’: {‘error_code’: ‘DH-905’, ‘error_type’: ‘Input_Exception’, ‘error_message’: ‘System is u’errorMessage’: ‘System is unable to fetch data due to incorrect parameters or no data present’}}Traceback (most recent call last):, ‘errorMessage’: ‘System is unable to fetch data due to incorrect parameters or no data present’}}

please help me how to get data on 3 minute candle frame.

Thanxs in advance

hi @Tradehull_Imran
i am facing issue while running codebase usage file:

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


client_code = ""
token_id    = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJkaGFuIiwicGFydG5lcklkIjoiIiwiZXhwIjoxNzYwMDI3NjI5L
tsl         = Tradehull(client_code , token_id  )  

pdb.set_trace()

ltp = tsl.get_ltp_data(names = ["ACC", "CIPLA"])




chart = tsl.get_historical_data(tradingsymbol = 'NIFTY',exchange = 'INDEX',timeframe="5")
data = tsl.get_historical_data(tradingsymbol = 'ACC',exchange = 'NSE',timeframe="5")



order_details = tsl.get_order_detail(orderid=102241104416927)
order_status  = tsl.get_order_status(orderid=102241104416927)
order_price   = tsl.get_executed_price(orderid=102241104416927)
order_time    = tsl.get_exchange_time(orderid=102241104416927)


positions = tsl.get_positions()
orderbook = tsl.get_orderbook()
tradebook = tsl.get_trade_book()
holdings = tsl.get_holdings()

error

C:\Users\DELL\Desktop\Dhan\Session3\Dhan codebase>py How_to_use_updated_codebase.py
Traceback (most recent call last):
  File "C:\Users\DELL\Desktop\Dhan\Session3\Dhan codebase\How_to_use_updated_codebase.py", line 5, in <module>
    from Dhan_Tradehull_V2 import Tradehull
  File "C:\Users\DELL\Desktop\Dhan\Session3\Dhan codebase\Dhan_Tradehull_V2.py", line 33
    def__init__(self,ClientCode:str,token_id:str):
                               ^
SyntaxError: invalid syntax

C:\Users\DELL\Desktop\Dhan\Session3\Dhan codebase>

Hi @Desh_Deepak_Verma

There are some updates to the DhanXTradehull codebase

Please connect us over LinkedIn, for all questions

hi @Tradehull_Imran
i am facing issue while running codebase usage file:

import datetime
import warnings
from dhanhq import marketfeed
import xlwings as xw
import pandas as pd
import time
import os

warnings.filterwarnings("ignore")

def get_instrument_file():
    global instrument_df
    current_date = time.strftime("%Y-%m-%d")
    expected_file = 'all_instrument ' + str(current_date) + '.csv'
    for item in os.listdir("Dependencies"):
        path = os.path.join(item)

        if (item.startswith('all_instrument')) and (current_date not in item.split(" ")[1]):
            if os.path.isfile("Dependencies\\" + path):
                os.remove("Dependencies\\" + path)

    if expected_file in os.listdir("Dependencies"):
        try:
            print(f"Reading existing file {expected_file}")
            instrument_df = pd.read_csv("Dependencies\\" + expected_file, low_memory=False)
        except Exception as e:
            print("This BOT Is Instrument file is not generated completely, Picking New File from Dhan Again")
            instrument_df = pd.read_csv("https://images.dhan.co/api-data/api-scrip-master.csv", low_memory=False)
            instrument_df.to_csv("Dependencies\\" + expected_file)
    else:
        # This will fetch instrument_df file from Dhan
        print("This BOT Is Picking New File From Dhan")
        instrument_df = pd.read_csv("https://images.dhan.co/api-data/api-scrip-master.csv", low_memory=False)
        instrument_df.to_csv("Dependencies\\" + expected_file)
    return instrument_df






# Excel sheet setup
wb = xw.Book("Websocket.xlsx")
sheet = wb.sheets['LTP']
client_id =
access_token = "eyJ
# Fetch the instrument file
current_date = time.strftime("%Y-%m-%d")
expected_file = 'all_instrument ' + str(current_date) + '.csv'
global instrument_df, old_instruments
old_instruments = list()
instrument_df = get_instrument_file()

def create_instruments(watchlist, stock_exchange):
    rows = dict()
    row = 1
    instruments = list()
    instrument_exchange = {'NSE': "NSE", 'BSE': "BSE", 'NFO': 'NSE', 'BFO': 'BSE', 'MCX': 'MCX', 'CUR': 'NSE', 'BSE_IDX': 'BSE', 'NSE_IDX': 'NSE'}
    exchange_id = {'NSE': marketfeed.NSE, 'BSE': marketfeed.BSE, 'MCX': marketfeed.MCX, 'NFO': marketfeed.NSE_FNO, 'BFO': marketfeed.BSE_FNO, 'IDX': marketfeed.IDX, 'BSE_IDX': marketfeed.IDX, 'NSE_IDX': marketfeed.IDX}

    for tradingsymbol in watchlist:
        try:
            row += 1
            exchange_ = stock_exchange[tradingsymbol]
            exchange = instrument_exchange[exchange_]
            security_id = instrument_df[
                ((instrument_df['SEM_TRADING_SYMBOL'] == tradingsymbol) | (instrument_df['SEM_CUSTOM_SYMBOL'] == tradingsymbol)) &
                (instrument_df['SEM_EXM_EXCH_ID'] == instrument_exchange[exchange])
            ].iloc[-1]['SEM_SMST_SECURITY_ID']
            exchange_segment = exchange_id[exchange_]
            # Subscribe to Quote mode for now, can be changed to Ticker or Depth as needed
            instruments.append((exchange_segment, str(security_id), marketfeed.Quote))
            rows[security_id] = row
        except Exception as e:
            print(f"Error: {e} for {tradingsymbol}")
            continue

    return instruments, rows

def run_feed(client_id, access_token, instruments):
    try:
        # Initialize DhanFeed
        data = marketfeed.DhanFeed(client_id, access_token, instruments)
        previous_watchlist = []
        rows = {}
        old_instruments = instruments

        while True:
            # Check for updated watchlist
            last_row_col1 = sheet.range('A1').end('down').row
            last_row_col2 = sheet.range('B1').end('down').row
            row = max(last_row_col1, last_row_col2)
            data_frame = sheet.range('A1').expand().options(pd.DataFrame, header=1, index=False).value
            stock_exchange = sheet.range(f'A2:B{row}').options(dict).value
            watchlist = data_frame['Script Name'].to_list()

            # If watchlist has changed, update the feed
            if watchlist != previous_watchlist:
                print("Watchlist changed. Reconnecting the feed...")

                # Create new instruments and row mappings before disconnecting
                new_instruments, new_rows = create_instruments(watchlist, stock_exchange)

                # Disconnect the current connection
                data.disconnect()
                print("Disconnected from WebSocket feed.")

                # Update previous watchlist and rows before reconnecting
                previous_watchlist = watchlist
                rows = new_rows
                old_instruments = new_instruments

                # Reconnect with the updated instruments
                data = marketfeed.DhanFeed(client_id, access_token, new_instruments)
                data.run_forever()

            # Start receiving data
            response = data.get_data()

            if response:
                print(f"{datetime.datetime.now().time()}: LTP Received")
                if 'LTP' in response.keys():
                    df = pd.DataFrame(response, index=[0])
                    security_id = response['security_id']
                    row = rows.get(int(security_id), None)

                    if row:
                        df = df[['LTP', 'avg_price', 'volume', 'total_sell_quantity', 'open', 'close', 'high', 'low']]
                        sheet.range(f'C{row}').value = df.values.tolist()

    except Exception as e:
        print(f"WebSocket connection error: {e}")
        print("Reconnecting Again...")
        # time.sleep(5)  # Short delay before reconnecting
        run_feed(client_id, access_token, instruments)  # Retry the connection

def main_loop():
    # Fetch initial instrument data and start the feed
    last_row_col1 = sheet.range('A1').end('down').row
    last_row_col2 = sheet.range('B1').end('down').row
    row = max(last_row_col1, last_row_col2)
    data_frame = sheet.range('A1').expand().options(pd.DataFrame, header=1, index=False).value
    stock_exchange = sheet.range(f'A2:B{row}').options(dict).value
    watchlist = data_frame['Script Name'].to_list()

    instruments, rows = create_instruments(watchlist, stock_exchange)
    run_feed(client_id, access_token, instruments)

if __name__ == "__main__":
    main_loop()

Error

Microsoft Windows [Version 10.0.19045.6332]
(c) Microsoft Corporation. All rights reserved.

C:\Users\DELL\Desktop\Dhan\Session3\3. Session3 - Codebase\Dhan codebase>PY Dhan_websocket.py
Reading existing file all_instrument 2025-10-10.csv
Error: single positional indexer is out-of-bounds for SILVER-27Aug2024-78000-PE
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 83300 PUT
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 83600 CALL
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 76800 PUT
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 78500 PUT
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 77000 PUT
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 81600 CALL
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 80100 CALL
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 78800 CALL
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 77300 CALL
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 79000 CALL
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 84100 PUT
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 76800 CALL
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 81900 PUT
Error: single positional indexer is out-of-bounds for BANKNIFTY 28 AUG 51600 CALL
Error: single positional indexer is out-of-bounds for NIFTY 29 AUG 23200 CALL
Watchlist changed. Reconnecting the feed...
Error: single positional indexer is out-of-bounds for SILVER-27Aug2024-78000-PE
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 83300 PUT
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 83600 CALL
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 76800 PUT
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 78500 PUT
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 77000 PUT
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 81600 CALL
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 80100 CALL
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 78800 CALL
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 77300 CALL
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 79000 CALL
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 84100 PUT
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 76800 CALL
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 81900 PUT
Error: single positional indexer is out-of-bounds for BANKNIFTY 28 AUG 51600 CALL
Error: single positional indexer is out-of-bounds for NIFTY 29 AUG 23200 CALL
Disconnected from WebSocket feed.
WebSocket connection error: server rejected WebSocket connection: HTTP 400
Reconnecting Again...
Watchlist changed. Reconnecting the feed...
Error: single positional indexer is out-of-bounds for SILVER-27Aug2024-78000-PE
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 83300 PUT
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 83600 CALL
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 76800 PUT
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 78500 PUT
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 77000 PUT
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 81600 CALL
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 80100 CALL
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 78800 CALL
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 77300 CALL
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 79000 CALL
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 84100 PUT
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 76800 CALL
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 81900 PUT
Error: single positional indexer is out-of-bounds for BANKNIFTY 28 AUG 51600 CALL
Error: single positional indexer is out-of-bounds for NIFTY 29 AUG 23200 CALL
Disconnected from WebSocket feed.
WebSocket connection error: server rejected WebSocket connection: HTTP 400
Reconnecting Again...
Watchlist changed. Reconnecting the feed...
Error: single positional indexer is out-of-bounds for SILVER-27Aug2024-78000-PE
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 83300 PUT
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 83600 CALL
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 76800 PUT
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 78500 PUT
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 77000 PUT
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 81600 CALL
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 80100 CALL
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 78800 CALL
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 77300 CALL
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 79000 CALL
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 84100 PUT
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 76800 CALL
Error: single positional indexer is out-of-bounds for SENSEX 06 SEP 81900 PUT
Error: single positional indexer is out-of-bounds for BANKNIFTY 28 AUG 51600 CALL
Error: single positional indexer is out-of-bounds for NIFTY 29 AUG 23200 CALL
Disconnected from WebSocket feed.



@Tradehull_Imran Sir, How to get the today candle(ohlc) after market closed? This code (today = chart.iloc[-1]) shows only day before yesterday candle on week days. Please resolve this issue

yes today’s candle data only available on next day after 9:15 am (daily candle data) 5 min candle data is available after market close

hi @Tradehull_Imran
“I am facing an issue while running the .Session6- 1st Live Algo file. The WebSocket is running, but the code base is not running properly. Please guide me on how to fix this problem.”`import pdb
from Dhan_Tradehull import Tradehull
import pandas as pd
import talib

client_code =
token_id =
tsl = Tradehull(client_code,token_id)

available_balance = tsl.get_balance()
leveraged_margin = available_balance*5
max_trades = 3
per_trade_margin = (leveraged_margin/max_trades)

watchlist = [‘MOTHERSON’, ‘OFSS’, ‘MANAPPURAM’, ‘BSOFT’, ‘CHAMBLFERT’, ‘DIXON’, ‘NATIONALUM’, ‘DLF’, ‘IDEA’, ‘ADANIPORTS’, ‘SAIL’, ‘HINDCOPPER’, ‘INDIGO’, ‘RECLTD’, ‘PNB’, ‘HINDALCO’, ‘RBLBANK’, ‘GNFC’, ‘ALKEM’, ‘CONCOR’, ‘PFC’, ‘GODREJPROP’, ‘MARUTI’, ‘ADANIENT’, ‘ONGC’, ‘CANBK’, ‘OBEROIRLTY’, ‘BANDHANBNK’, ‘SBIN’, ‘HINDPETRO’, ‘CANFINHOME’, ‘TATAMOTORS’, ‘LALPATHLAB’, ‘MCX’, ‘TATACHEM’, ‘BHARTIARTL’, ‘INDIAMART’, ‘LUPIN’, ‘INDUSTOWER’, ‘VEDL’, ‘SHRIRAMFIN’, ‘POLYCAB’, ‘WIPRO’, ‘UBL’, ‘SRF’, ‘BHARATFORG’, ‘GRASIM’, ‘IEX’, ‘BATAINDIA’, ‘AARTIIND’, ‘TATASTEEL’, ‘UPL’, ‘HDFCBANK’, ‘LTF’, ‘TVSMOTOR’, ‘GMRINFRA’, ‘IOC’, ‘ABCAPITAL’, ‘ACC’, ‘IDFCFIRSTB’, ‘ABFRL’, ‘ZYDUSLIFE’, ‘GLENMARK’, ‘TATAPOWER’, ‘PEL’, ‘IDFC’, ‘LAURUSLABS’, ‘BANKBARODA’, ‘KOTAKBANK’, ‘CUB’, ‘GAIL’, ‘DABUR’, ‘TECHM’, ‘CHOLAFIN’, ‘BEL’, ‘SYNGENE’, ‘FEDERALBNK’, ‘NAVINFLUOR’, ‘AXISBANK’, ‘LT’, ‘ICICIGI’, ‘EXIDEIND’, ‘TATACOMM’, ‘RELIANCE’, ‘ICICIPRULI’, ‘IPCALAB’, ‘AUBANK’, ‘INDIACEM’, ‘GRANULES’, ‘HDFCAMC’, ‘COFORGE’, ‘LICHSGFIN’, ‘BAJAJFINSV’, ‘INFY’, ‘BRITANNIA’, ‘M&MFIN’, ‘BAJFINANCE’, ‘PIIND’, ‘DEEPAKNTR’, ‘SHREECEM’, ‘INDUSINDBK’, ‘DRREDDY’, ‘TCS’, ‘BPCL’, ‘PETRONET’, ‘NAUKRI’, ‘JSWSTEEL’, ‘MUTHOOTFIN’, ‘CUMMINSIND’, ‘CROMPTON’, ‘M&M’, ‘GODREJCP’, ‘IGL’, ‘BAJAJ-AUTO’, ‘HEROMOTOCO’, ‘AMBUJACEM’, ‘BIOCON’, ‘ULTRACEMCO’, ‘VOLTAS’, ‘BALRAMCHIN’, ‘SUNPHARMA’, ‘ASIANPAINT’, ‘COALINDIA’, ‘SUNTV’, ‘EICHERMOT’, ‘ESCORTS’, ‘HAL’, ‘ASTRAL’, ‘NMDC’, ‘ICICIBANK’, ‘TORNTPHARM’, ‘JUBLFOOD’, ‘METROPOLIS’, ‘RAMCOCEM’, ‘INDHOTEL’, ‘HINDUNILVR’, ‘TRENT’, ‘TITAN’, ‘JKCEMENT’, ‘ASHOKLEY’, ‘SBICARD’, ‘BERGEPAINT’, ‘JINDALSTEL’, ‘MFSL’, ‘BHEL’, ‘NESTLEIND’, ‘HDFCLIFE’, ‘COROMANDEL’, ‘DIVISLAB’, ‘ITC’, ‘TATACONSUM’, ‘APOLLOTYRE’, ‘AUROPHARMA’, ‘HCLTECH’, ‘LTTS’, ‘BALKRISIND’, ‘DALBHARAT’, ‘APOLLOHOSP’, ‘ABBOTINDIA’, ‘ATUL’, ‘UNITDSPR’, ‘PVRINOX’, ‘SIEMENS’, ‘SBILIFE’, ‘IRCTC’, ‘GUJGASLTD’, ‘BOSCHLTD’, ‘NTPC’, ‘POWERGRID’, ‘MARICO’, ‘HAVELLS’, ‘MPHASIS’, ‘COLPAL’, ‘CIPLA’, ‘MGL’, ‘ABB’, ‘PIDILITIND’, ‘MRF’, ‘LTIM’, ‘PAGEIND’, ‘PERSISTENT’]

traded_wathclist =

while True:
for stock_name in watchlist:
print(stock_name)

    chart = tsl.get_intraday_data(stock_name, 'NSE', 1)
    chart['rsi'] = talib.RSI(chart['close'], timeperiod=14) #pandas

    bc   = chart.iloc[-2] #pandas  breakout candle
    ic   = chart.iloc[-3] #pandas  inside candle
    ba_c = chart.iloc[-4] #pandas  base candle

    uptrend = bc['rsi'] > 50
    downtrend = bc['rsi'] < 49
    inside_candle_formed = (ba_c['high'] > ic['high']) and (ba_c['low'] < ic['low'])


    upper_side_breakout = bc['high'] > ba_c['high']
    down_side_breakout  = bc['low']  < ba_c['low']

    no_repeat_order = stock_name not in traded_wathclist
    max_order_limit = len(traded_wathclist) <= max_trades


    if uptrend and inside_candle_formed and upper_side_breakout and no_repeat_order and max_order_limit:
        print(stock_name, "is in uptrend, Buy this script")
        qty = int(per_trade_margin/bc['close'])
        buy_entry_orderid = tsl.order_placement(stock_name,'NSE', 1, 0, 0, 'MARKET', 'BUY', 'MIS')
        traded_wathclist.append(stock_name)



    if downtrend and inside_candle_formed and down_side_breakout and no_repeat_order and max_order_limit:
        print(stock_name, "is in downtrend SELL this script")
        qty = int(per_trade_margin/bc['close'])
        sell_entry_orderid = tsl.order_placement(stock_name,'NSE', 1, 0, 0, 'MARKET', 'SELL', 'MIS')
        traded_wathclist.append(stock_name)

Erorr :

Microsoft Windows [Version 10.0.26100.6725]
(c) Microsoft Corporation. All rights reserved.

C:\Users\Desh Deppak Verma\OneDrive\Desktop\Dhan\6. Session6- 1st Live Algo\1st live Algo>py "Dhan_codebase usage.py"
-----Logged into Dhan-----
reading existing file all_instrument 2025-10-15.csv
Got the instrument file
MOTHERSON
intraday_minute_data() missing 2 required positional arguments: 'from_date' and 'to_date'
Traceback (most recent call last):
  File "C:\Users\Desh Deppak Verma\OneDrive\Desktop\Dhan\6. Session6- 1st Live Algo\1st live Algo\Dhan_Tradehull.py", line 253, in get_intraday_data
    ohlc = self.Dhan.intraday_minute_data(str(security_id),exchangeSegment,instrument_type)
TypeError: intraday_minute_data() missing 2 required positional arguments: 'from_date' and 'to_date'
Traceback (most recent call last):
  File "Dhan_codebase usage.py", line 28, in <module>
    chart['rsi'] = talib.RSI(chart['close'], timeperiod=14) #pandas
TypeError: 'NoneType' object is not subscriptable

`

Hi @Desh_Deepak_Verma ,

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='NIFTY', exchange='INDEX', timeframe="DAY") 
data = tsl.get_historical_data(tradingsymbol='ACC', exchange='NSE', timeframe="1")

Do update to our latest codebase version 3.0.6:

  • Open Command Prompt: Press Win, type cmd, and press Enter.
  • Install Dhan-Tradehull: Run pip install Dhan-Tradehull
  • Confirm the installation by running pip show Dhan-Tradehull

Guide to use the updated codebase:
Refer the below pypi link for more details:

Hello @Tradehull_Imran
I am getting this error when i run the script, also even tough the script runs, it doesnt places order , could you please help on this
I am using Dhan_Tradehull_V2.py and updated codebase 3.0

D:\ALgo Programming\9. Session9- 3rd Live Algo\Running Algo>py “4.1 small code Indicator Based Scanner.py”
Codebase Version 2.2 : Rate Limits
-----Logged into Dhan-----
reading existing file all_instrument 2025-10-16.csv
Got the instrument file
Scanner Started to scan at 12:55:47.598878
Scanning TATASTEEL 2025-10-16 12:55:47.598878
Checking TATASTEEL…
:white_check_mark: BUY SIGNAL: TATASTEEL
Traceback (most recent call last):
File “D:\ALgo Programming\9. Session9- 3rd Live Algo\Running Algo\Dhan_Tradehull_V2.py”, line 139, in order_placement
orderid = order[“data”][“orderId”]
KeyError: ‘orderId’
Traceback (most recent call last):
File “D:\ALgo Programming\9. Session9- 3rd Live Algo\Running Algo\Dhan_Tradehull_V2.py”, line 139, in order_placement
orderid = order[“data”][“orderId”]
KeyError: ‘orderId’
Traceback (most recent call last):
File “D:\ALgo Programming\9. Session9- 3rd Live Algo\Running Algo\Dhan_Tradehull_V2.py”, line 139, in order_placement
orderid = order[“data”][“orderId”]
KeyError: ‘orderId’
Scan cycle completed. Waiting before next scan…

Hi @Priyesh_Sharma
Please share code as well

@Tradehull_Imran
Here is the code

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 ta

Client details

client_code = “19”
token_id = “eA”
tsl = Tradehull(client_code, token_id)

watchlist = [‘TATASTEEL’]

available_balance = tsl.get_balance()
leveraged_margin = available_balance * 5
max_trades = 1
per_trade_margin = (leveraged_margin / max_trades)
max_loss = (available_balance * 1) / 100 * -2

positions = {} # {stock_name: {‘status’: ‘Buy’/‘Sell’, ‘entry_price’: price, ‘qty’: qty}}
traded_watchlist =

while True:
live_pnl = tsl.get_live_pnl()
current_time = datetime.datetime.now().time()

if current_time < datetime.time(9, 15):
    print("wait for market to start", current_time)
    continue

if (current_time > datetime.time(15, 00)) or (live_pnl < max_loss):
    I_want_to_trade_no_more = tsl.kill_switch('ON')
    order_details = tsl.cancel_all_orders()
    print("MAX LOSS or Market is over, Bye Bye see you tomorrow", current_time)
    break

try:
    # Get ltp
    all_ltp = tsl.get_ltp_data(names=watchlist)
    
    current_time = datetime.datetime.now().time()
    print("Scanner Started to scan at ", current_time)
    
    for stock_name in watchlist:
        try:
            current_time = datetime.datetime.now()
            print(f"Scanning {stock_name}  ", current_time)
            time.sleep(0.1)  # Prevent API rate limit issues
            
            print(f"Checking {stock_name}...")  # Fixed: was stock_name, should be name
            chart = tsl.get_historical_data(tradingsymbol=stock_name, exchange='NSE', timeframe="5")
            if chart is None or not isinstance(chart, pd.DataFrame):
                print(f"Failed to retrieve historical data for {stock_name}")
                continue
            
            # Calculate indicators
            chart['rsi'] = talib.RSI(chart['close'], timeperiod=14)
            chart['CDLENGULFING'] = talib.CDLENGULFING(chart['open'], chart['high'], chart['low'], chart['close'])
            
            # Supertrend indicators
            indi = ta.supertrend(chart['high'], chart['low'], chart['close'], 10, 2)
            chart = pd.concat([chart, indi], axis=1, join='inner')
            
            indi = ta.supertrend(chart['high'], chart['low'], chart['close'], 10, 4)
            chart = pd.concat([chart, indi], axis=1, join='inner')
            
            indi = ta.supertrend(chart['high'], chart['low'], chart['close'], 10, 6)
            chart = pd.concat([chart, indi], axis=1, join='inner')

            chart['MFI'] = talib.MFI(chart['high'], chart['low'], chart['close'], chart['volume'], timeperiod=14)
            
            cc_5 = chart.iloc[-1]  # Most recent running candle
            cc_3 = chart.iloc[-2]  # Previous completed candle
            
            # Get LTP from all_ltp with error handling
            try:
                ltp = all_ltp.get(stock_name)
            except:
                print(f"LTP not available for {stock_name}")
                continue
            
            # Buy entry conditions
            bc1 = cc_5['rsi'] > 40 and cc_5['MFI'] > 40
            bc2 = (cc_5['SUPERTd_10_2.0'] == 1)
            bc3 = (cc_5['SUPERTd_10_4.0'] == 1)
            bc4 = (cc_5['SUPERTd_10_6.0'] == 1)
            
            # Sell entry conditions
            sc1 = cc_5['rsi'] < 30
            sc2 = (cc_5['SUPERTd_10_2.0'] == -1)
            sc3 = (cc_5['SUPERTd_10_4.0'] == -1)
            sc4 = (cc_5['SUPERTd_10_6.0'] == -1)

            no_repeat_order = stock_name not in traded_watchlist
            max_order_limit = len(traded_watchlist) <= max_trades
            
            if bc1 :#and bc2 and bc3 and bc4 and no_repeat_order and max_order_limit:
                print("✅ BUY SIGNAL: ", stock_name, "\t")
                position = 'Buy'
                #print(f"{stock_name} RSI: {cc_5['rsi']:.2f}, MFI: {cc_5['MFI']:.2f}, LTP: {ltp}")

                sl_price = round((cc_5['close'] * 0.99), 1)
                qty = 1 #int(per_trade_margin / cc_5['close'])
                sell_price = round((cc_5['close'] * 1.01), 1)

                buy_entry_orderid = tsl.order_placement(stock_name, 'NSE', qty, 0, 0, 'MARKET', 'BUY', 'MIS')
                sl_orderid = tsl.order_placement(stock_name, 'NSE', qty, 0, sl_price, 'STOPMARKET', 'SELL', 'MIS')
                sell_orderid = tsl.order_placement(stock_name, 'NSE', qty, 0, sell_price, 'LIMIT', 'SELL', 'MIS')

                traded_watchlist.append(stock_name)
            
            if sc1 and sc2 and sc3 and sc4 and no_repeat_order and max_order_limit:
                print("❌ SELL SIGNAL: ", stock_name, "\t")
                position = 'Sell'
                #print(f"{stock_name} RSI: {cc_5['rsi']:.2f}, LTP: {ltp}")

                sl_price          = round((cc_5['close']*1.01),1)
                qty               = int(per_trade_margin/cc_5['close'])
                buy_price         = round((cc_5['close']*0.99),1)

                buy_entry_orderid = tsl.order_placement(stock_name,'NSE', qty, 0, 0, 'MARKET', 'SELL', 'MIS')
                sl_orderid        = tsl.order_placement(stock_name,'NSE', qty, 0, sl_price, 'STOPMARKET', 'BUY', 'MIS')
                sell_orderid = tsl.order_placement(stock_name, 'NSE', qty, 0, sell_price, 'LIMIT', 'SELL', 'MIS')
                
                traded_watchlist.append(stock_name)

                # Exit conditions
            if stock_name in positions:
                if positions[stock_name]['status'] == 'Buy':
                    if (cc_5['SUPERTd_10_2'] == -1 or
                        cc_5['SUPERTd_10_4'] == -1 or
                        cc_5['SUPERTd_10_6'] == -1):
                        order_details = tsl.cancel_all_orders(stock_name)
                        print(f"Exit Buy {stock_name} (One or more Supertrends turned red)")
                 

            if stock_name in positions:
                if positions[stock_name]['status'] == 'Buy':
                    if (cc_5['SUPERTd_10_2'] == 1 or
                        cc_5['SUPERTd_10_4'] == 1 or
                        cc_5['SUPERTd_10_6'] == 1):
                        order_details = tsl.cancel_all_orders(stock_name)
                        print(f"Exit Sell {stock_name} (One or more Supertrends turned green)")
            
        except Exception as stock_error:
            print(f"Error processing {stock_name}: {stock_error}")
            continue
    
    print("Scan cycle completed. Waiting before next scan...")
    time.sleep(30)  # Wait 30 seconds before next full scan cycle
    
except Exception as e:
    print(f"Main loop error: {e}")
    print("Waiting 60 seconds before retrying...")
    time.sleep(30)
    continue

@Tradehull_Imran
Also Getting issues with Supertrend also in the above code
While running it at 9.20 am
here is the error
D:\ALgo Programming\9. Session9- 3rd Live Algo\Running Algo>py “4.1 small code Indicator Based Scanner.py”
Codebase Version 2.2 : Rate Limits
-----Logged into Dhan-----
reading existing file all_instrument 2025-10-16.csv
Got the instrument file
Scanner Started to scan at 09:20:12.829371
Scanning CANBK 2025-10-16 09:20:12.829371
Checking CANBK…
Error processing CANBK: ‘SUPERTd_10_2.0’
Scan cycle completed. Waiting before next scan…
Scanner Started to scan at 09:20:47.846151
Scanning CANBK 2025-10-16 09:20:47.846151
Checking CANBK…
Error processing CANBK: ‘SUPERTd_10_2.0’
Scan cycle completed. Waiting before next scan…
Traceback (most recent call last):
File “4.1 small code Indicator Based Scanner.py”, line 153, in
time.sleep(30) # Wait 30 seconds before next full scan cycle

Hi @Priyesh_Sharma ,

  1. Firstly before placing order check all the parameters that are passed are correct and make sure you have generated the access token for today.
  2. It is just a column name mismatch or join drop. print the column list once, confirm if it’s SUPERTd_10_2 or SUPERTd_10_2.0, and update your condition lines accordingly.

Let me know if you face any challenge.
Do update to our latest codebase version 3.0.6:

  • Open Command Prompt: Press Win, type cmd, and press Enter.
  • Install Dhan-Tradehull: Run pip install Dhan-Tradehull
  • Confirm the installation by running pip show Dhan-Tradehull

Guide to use the updated codebase:
Refer the below pypi link for more details:

hi sir ,
i learnt a lot from your algo series. I am working on option chain atm_strike, option_chain = tsl.get_option_chain(‘nifty’, ‘INDEX’, 0, num_strikes=10) but the prbolem is data from this option chain differs from NSE website option i.e. chain OI, change in OI, Volume and IV these four column gave wrong results but rest all columns like LTP are accurate. For PCR i need OI and change In OI. Can you please help me in this . I also attached the screenshot for the same comparing both tables form dhan api and NSE

Hello @Tradehull_Imran

I am still unable to place order on Dhan getting this error when i run the script, also even though the script runs, it doesnt places order , could you please help on this
I am using Dhan_Tradehull_V2.py and updated codebase 3.0

D:\ALgo Programming\9. Session9- 3rd Live Algo\Running Algo>py “Multi timeframe Algo.py”
Codebase Version 2.2 : Rate Limits
-----Logged into Dhan-----
reading existing file all_instrument 2025-10-17.csv
Got the instrument file
ADANIPOWER
ADANIPOWER is in uptrend, Buy this script
Traceback (most recent call last):
File “D:\ALgo Programming\9. Session9- 3rd Live Algo\Running Algo\Dhan_Tradehull_V2.py”, line 139, in order_placement
orderid = order[“data”][“orderId”]
KeyError: ‘orderId’
Traceback (most recent call last):
File “D:\ALgo Programming\9. Session9- 3rd Live Algo\Running Algo\Dhan_Tradehull_V2.py”, line 139, in order_placement
orderid = order[“data”][“orderId”]
KeyError: ‘orderId’
Traceback (most recent call last):
File “D:\ALgo Programming\9. Session9- 3rd Live Algo\Running Algo\Dhan_Tradehull_V2.py”, line 139, in order_placement
orderid = order[“data”][“orderId”]
KeyError: ‘orderId’
ADANIPOWER
ADANIPOWER
ADANIPOWER

The Code is given below

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

Client details

client_code = “19”
token_id = “”
tsl = Tradehull(client_code, token_id)

available_balance = tsl.get_balance()
leveraged_margin = available_balance5
max_trades = 5
per_trade_margin = (leveraged_margin/max_trades)
max_loss = (available_balance
1)/100*-4

watchlist = [‘ADANIPOWER’]
traded_wathclist =

while True:

live_pnl = tsl.get_live_pnl()
current_time = datetime.datetime.now().time()

if current_time < datetime.time(9, 15):
	print("wait for market to start", current_time)
	continue


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



for stock_name in watchlist:
	time.sleep(0.1)
	print(stock_name)



	# Conditions that are on 1 minute timeframe
	chart_5        = tsl.get_intraday_data(stock_name, 'NSE', 5)       # 5 minute chart   # this call has been updated to get_historical_data call, 
	chart_5        = tsl.get_historical_data(tradingsymbol = stock_name,exchange = 'NSE',timeframe="5")


	chart_5['rsi'] = talib.RSI(chart_5['close'], timeperiod=14) #pandas
	cc_5           = chart_5.iloc[-2]  #pandas  completed candle of 5 min timeframe
	uptrend        = cc_5['rsi'] > 40
	downtrend      = cc_5['rsi'] < 30


	# Conditions that are on 5 minute timeframe
	chart_5        = tsl.get_intraday_data(stock_name, 'NSE', 5)       # 5 minute chart
	chart_5          = tsl.get_historical_data(tradingsymbol = stock_name,exchange = 'NSE',timeframe="5") # this call has been updated to get_historical_data call, 
	chart_5['upperband'], chart_5['middleband'], chart_5['lowerband'] = talib.BBANDS(chart_5['close'], timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)
	cc_5           = chart_5.iloc[-1]   # pandas
	ub_breakout    = cc_5['high'] > cc_5['upperband']
	lb_breakout    = cc_5['low'] < cc_5['lowerband']

	no_repeat_order = stock_name not in traded_wathclist
	max_order_limit = len(traded_wathclist) <= max_trades


	if uptrend and no_repeat_order and max_order_limit:
		print(stock_name, "is in uptrend, Buy this script")

		sl_price          = round((cc_5['close']*0.98),1)
		qty               = int(per_trade_margin/cc_5['close'])
		sell_price        = round((cc_5['close']*1.02),1)

		buy_entry_orderid = tsl.order_placement(stock_name,'NSE', qty, 0, 0, 'MARKET', 'BUY', 'MIS')
		sl_orderid        = tsl.order_placement(stock_name,'NSE', qty, 0, sl_price, 'STOPMARKET', 'SELL', 'MIS')
		sell_orderid      = tsl.order_placement(stock_name,'NSE', qty, 0, sell_price, 'LIMIT', 'SELL', 'MIS')

		traded_wathclist.append(stock_name)

	if downtrend and no_repeat_order and max_order_limit:
		print(stock_name, "is in downtrend, Sell this script")

		sl_price          = round((cc_5['close']*1.02),1)
		qty               = int(per_trade_margin/cc_5['close'])
		buy_price          = round((cc_5['close']*0.98),1)

		buy_entry_orderid = tsl.order_placement(stock_name,'NSE', qty, 0, 0, 'MARKET', 'SELL', 'MIS')
		sl_orderid        = tsl.order_placement(stock_name,'NSE', qty, 0, sl_price, 'STOPMARKET', 'BUY', 'MIS')
		sell_orderid      = tsl.order_placement(stock_name,'NSE', qty, 0, buy_price, 'LIMIT', 'SELL', 'MIS')
		traded_wathclist.append(stock_name)

Hi @akki .

OI data is delayed by 3 minutes always, this delay is set from exchange side. also the OI data in excel divide it by lot size

1 Like

Hi @Priyesh_Sharma ,

If you are using Codebase version then you don’t require Dhan_Tradehull_V2 file within your folder.

Check the below Video reference on how to use codebase:

pls help me, how can i solve this problem

note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for TA-Lib
Failed to build TA-Lib

error: failed-wheel-build-for-install

Hello @Tradehull_Imran sir,
Please share more details about this opportunity if it is still open.