Learn Algo Trading with Python | Codes | Youtube Series

after spending time on this, below are the only secor available to fetch are below.

NIFTY
NIFTY PVT BANK
NIFTY 500
BANKNIFTY
FINNIFTY
NIFTY FMCG
NIFTYIT
NIFTY MEDIA
NIFTY METAL
NIFTY PHARMA
NIFTY PSU BANK
NIFTY REALTY
NIFTY CONSR DURBL
Nifty Oil and Gas
Nifty Healthcare
Nifty India Digital
Nifty India Manufacturing

Hi Imran, i am unable to install TA-Lib, and also unable to download the zip file

try this

data = tsl.get_historical_data(tradingsymbol='NIFTY', exchange='INDEX', timeframe="15")
print(data)

Same issue with me. We are all suggested to use Python 3.8.0 version. But installation of pandas_ta needs minimum 3.12 python version as pr GROK. Imran Sir, Rahul Sir, please confirm, about using pyhton 3.12 version to use the codes shared during the Algo trading series both initial and advanced sessions. Please reply sir.

sir i am getting the error in the screenshot submitted with the following code. kindly check @Tradehull_Imran

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 = “1105938434”
access_token = "ACCESS TOKEN HIDDEN


"

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()

https://private-poc.madefortrade.in/u/tradehull_imran
@Tradehull_Imran Good Evening sir. Here is the Code I tried running “Algo Testing”,
Its giving the following error at cmd prompt sir. ERROR:
C:\Users\Admin\Desktop\TRADES\Dhan Algo\DHAN Advanced Algo Trading Series\Session 5pip install pandas_ta
ERROR: Could not find a version that satisfies the requirement pandas_ta (from versions: none)
ERROR: No matching distribution found for pandas_ta

Code:
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

client_code = “"
token_id = "
___________________”
tsl = Tradehull(client_code,token_id)

WatchList = [‘ADANIPORTS’,‘SBIN’,‘TATASTEEL’,‘BAJAJFINSV’, ‘RELIANCE’, ‘TCS’, ‘HCLTECH’, ‘NTPC’, ‘BHARTIARTL’, ‘WIPRO’, ‘BAJFINANCE’, ‘INDUSINDBK’, ‘KOTAKBANK’, ‘HINDALCO’, ‘AXISBANK’, ‘MARUTI’, ‘EICHERMOT’, ‘COALINDIA’, ‘TITAN’, ‘UPL’, ‘HINDUNILVR’, ‘ITC’, ‘NESTLEIND’, ‘APOLLOHOSP’, ‘GRASIM’, ‘BRITANNIA’, ‘POWERGRID’, ‘SBILIFE’]
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’)
sheet = wb.sheets[‘Sheet1’]
reentry = “yes” # “yes/no”

completed_orders_sheet = wb.sheets[‘completed_orders’]
completed_orders =

for name in watchlist:
orderbook[name] = single_order.copy()

while True: # To make the Algo loop continued in the framed time schedule.

for name in watchlist:

    orderbook_df = pd.DataFrame(orderbook).T 
    sheet.range('A1').value = orderbook_df
    
    current_time = datetime.datetime.now()
    print(f"Scanning {name}")
    chart = tsl.get_historical_data(tradingsymbol = name,exchange = 'NSE',timeframe = "5" )

    chart['rsi'] = talib.RSI(chart['close'],timeperiod=14)

    cc   = chart.iloc[-2]
    
    # Buy Entry Conditions
    bc1 = cc['rsi'] > 60
    bc2 = orderbook[name]['trade'] is None  # To avoid repeated entry, while exit is in pending. 


    # Sell Entry Conditions
    sc1 = cc['rsi'] < 40
    sc2 = orderbook[name]['trade'] is None  # To avoid repeated exit, while exit is in pending.

    if bc1 and bc2:
        print("buy", name, "\t")
        orderbook[name]['name']           = name
        orderbook[name]['date']           = str(current_time.date())
        orderbook[name]['entry_time']     = str(current_time.time())[:8]  # [:8] indicates no. of places 
        orderbook[name]['buy_sell']       = "BUY"
        orderbook[name]['qty']            = "qty"


        entry_orderid                     = tsl.order_placement(tradingsymbol=name, exchange='NSE', quantity=orderbook[name]['qty'], 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.01, 1)
        orderbook[name]['sl']          = round(orderbook[name]['entry_price']*0.99, 1)
        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]['trade']       = "yes"



    if orderbook[name]['traded'] == "yes":
        bought  = orderbook[name]['buy_sell'] == "BUY"

        if bought:
            sl_hit    = tsl.get_order_status(OrderID=orderbook[name]['sl_orderid']) == "Traded" # "Traded" is Dhan terminology
            tg_hit    = cc['close'] > orderbook[name]['tg']


            if sl_hit:
                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']         = (orderbook[name]['exit_price'] - orderbook[name]['entry_price'])*orderbook[name]['qty']
                orderbook[name]['remark']      = "Bought_SL_hit"

                if reentry == "yes":
                    completed_orders.append(orderbook[name])
                    orderbook[name] = None
                

            if tg_hit:
                tsl.cancel_order(OrderID=orderbook[name]['sl_orderid'])
                square_off_buy_order           = tsl.order_placement(tradingsymbol=orderbook[name]['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]['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']      = "Bought_TG_hit"

                if reentry == "yes":
                    completed_orders.append(orderbook[name])
                    orderbook[name] = None

Please help in this problem

Hi @Tradehull_Imran ,
we are getting option greek (‘delta’) value wrong for weekly expiry strikes Nifty option chain
but we are getting correct value for stocks options with monthly expiry as i use below code
Note: i believe NIFTY 50 and NIFTY asset same while fetching delta value

delta_values = tsl.get_option_greek(strike=25200, expiry=0, asset=‘NIFTY’, interest_rate=10, flag=‘delta’, scrip_type=‘CE’)

Hi Everyone,
I am happy to share this.

For all the traders who have watched and practiced Dhan x Tradehull Algorithmic Trading series.
You all possess a valuable skill. A Big one.

For those seeking job opportunities, we are working on connecting you with prestigious quant roles where these skills are valuable.

Gratitude @PravinJ @Dhan

2 Likes

Sir algo run karne ke leae dhantradehull ko update kar ke dhantradehull_v2.py kar liea to ab algo run karne ke leae websocket phale run nahi karna hai sirf direct algo run kare ki pahale dhantradehull_v2.py run kar aur bad me algo ko

i am delighted to join but i have developed all insane code with the help of AI. Feel free to ping me sir if at all needed.

Hi @Tradehull_Imran Sir ,
we are getting option greek (‘delta’) value wrong for weekly expiry strikes Nifty option chain
but we are getting correct value for stocks options with monthly expiry as i use below code
Note: i believe NIFTY 50 and NIFTY asset same while fetching delta value

delta_values = tsl.get_option_greek(strike=25200, expiry=0, asset=‘NIFTY’, interest_rate=10, flag=‘delta’, scrip_type=‘CE’)

Hello @Tradehull_Imran
Hi! Thank you so much for sharing this exciting news. I found the Dhan x Tradehull Algorithmic Trading series to be an invaluable resource, and I truly appreciate the effort that went into it. I am very interested in exploring the job opportunities you mentioned and would love to know the next steps for connecting with those prestigious quant roles.

Hi @Tradehull_Imran Sir ,
we are getting option greek (‘delta’) value wrong for weekly expiry strikes Nifty option chain
but we are getting correct value for stocks options with monthly expiry as i use below code
Note: i believe NIFTY 50 and NIFTY asset same while fetching delta value

delta_values = tsl.get_option_greek(strike=25200, expiry=0, asset=‘NIFTY’, interest_rate=10, flag=‘delta’, scrip_type=‘CE’)

Hi @Tradehull_Imran, I’ve been waiting for this news since the Advanced Algo Series!

The Dhan x Tradehull sessions have been incredibly insightful—I’ve learned a lot, especially around structuring algos, integrating APIs, and backtesting strategies with custom indicators. I’ve written a few algos myself and tested them across different market conditions. The hands-on coding and real-world logic really helped sharpen my understanding.

I’m definitely keen to explore the quant roles you mentioned. Please let me know if any additional details or steps are needed to move forward.

Thanks again for creating such a powerful learning experience!

Hi Imran,

I am always getting this error

Exception: {‘status’: ‘failure’, ‘remarks’: {‘error_code’: ‘DH-904’, ‘error_type’: ‘Rate_Limit’, ‘error_message’: ‘Too many requests on server from single user breaching rate limits. Try throttling API calls.’}, ‘data’: {‘errorType’: ‘Rate_Limit’, ‘errorCode’: ‘DH-904’, ‘errorMessage’: ‘Too many requests on server from single user breaching rate limits. Try throttling API calls.’}}

This is the first time I am using the api. Can you please help to identify

have trouble in installing pandas-ta

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