Learn Algo Trading with Python | Codes | Youtube Series

I GUESS THE INTRADAY DATA FETCHING FUNCTION DOES NOT WORK, IF IT DOES NOT THEN WHY IS IT EVEN THERE IN THE FIRST PLACE??? I KNOW GET HISTORICAL DATA WORKS BUT WHY NOT THIS??

    try:
        intraday_response = client.intraday_minute_data(
            security_id="13",
            exchange_segment="I",
            instrument_type="INDEX",
            from_date="2025-03-13",
            to_date="2025-03-13",
            interval=1
        )
        
        if intraday_response.get("status") == "success":
            data = intraday_response.get("data", [])
            print("\nIntraday Minute Data:")
            for entry in data:
                print(entry)
        else:
            print("\nIntraday Minute Data Error:")
            print(intraday_response)
    except Exception as e:
        print("Error fetching intraday minute data:", e)

REPONSE

Intraday Minute Data Error:
{'status': 'failure', 'remarks': {'error_code': 'DH-905', 'error_type': 'Input_Exception', 'error_message': 'Missing required fields, bad values for parameters etc.'}, 'data': {'errorType': 'Input_Exception', 'errorCode': 'DH-905', 'errorMessage': 'Missing required fields, bad values for parameters etc.'}}

thanks

live_pnl =tsl.get_live_pnl()
^
IndentationError: unindent does not match any outer indentation level

Hi @Jana_HS ,

The sqn_lib file must be present in the same folder where you have your main file.

Hi @Jana_HS ,

Download the sqn_lib file from the below url:

1 Like

Hi @Jana_HS ,


Click on Tab Size and then click on convert indentation to tabs. Save the file and re run.


What are the the things I need to do to solve this error and go ahead for my algo series!

Hi @vedant_patil ,

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")
2 Likes

hi @Tradehull_Imran Sir, what should be the parameters in entry order in below line in case I wish to execute a carry forward trade? Currently, with below command all trades via algo are getting executed as Intraday only. However, I would like to place the trades as carry forward (overnight) instead of intraday. thanks!

Blockquote
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’)

Change trade_type =‘CNC’

2 Likes

thank you @Siddhesh_Amrute !

@Tradehull_Imran Sir,
Can the below piece of code be written this way?

Original,

Blockquote
while True:
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

Can it be written as?

Blockquote
while True:
all_ltp = tsl.get_ltp_data(names = 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
for name in watchlist:

that is basically can the update of excel be done together for each iteration of the while loop instead of each name in watchlist (current method)?

Hello @Tradehull_Imran
‘NoneType’ has no attribute ‘iloc’
I am getting an error generating previous historical data from Session 9, in the pre market scanner. Please note that my Token ID and Access token are valid and active.
Kindly let me know, how to proceed further.

Thanks

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

client_code = "1104872458"
token_id    = "yJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJkaGFuIiwicGFydG5lcklkIjoiIiwiZXhwIjoxNzQ0MjgzMzQ1LCJ0b2tlbkNvbnN1bWVyVHlwZSI6IlNFTEYiLCJ3ZWJob29rVXJsIjoiIiwiZGhhbkNsaWVudElkIjoiMTEwNDg3MjQ1OCJ9.-7jHjgk2u9Hw_al-PmJUEYyxNdTLhb5JD1fji7VgF5g0j-28stqmtvMqRQV0NsCsqqxPr-BN9fR1O3aWsbhRSw"
tsl = Tradehull(client_code,token_id)

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


body_dict = {}
tarde_info = {}



for name in pre_market_watchlist:
	time.sleep(1)
	print(f"Pre market scanning {name}")
	daily_data = tsl.get_historical_data(name, 'NSE', "DAY")
	ldc = daily_data.iloc[-1]  #last_day_candle
	body_percentage = ((ldc['close'] - ldc['open'])/ldc['open'])*100
	body_dict[name] = round(body_percentage, 2)



script_having_max_body = max(body_dict, key=body_dict.get)
daily_data = tsl.get_historical_data(tradingsymbol = script_having_max_body, exchange = 'NSE',timeframe="DAY")
ldc = daily_data.iloc[-1]  #last_day_candle
tarde_info = {"Direction":"buy", "level":ldc['high']}


print(script_having_max_body)
print(tarde_info)



![1|690x298](upload://tDmSodiP0xzDinf4KGHWmaY9GVQ.png)

Good noon @Tradehull_Imran Sir,

My Stop loss Code is-

   sl_order_id = tsl.order_placement(
                        option_symbol, 
                        "NFO", 
                        client_qty, 
                        0, 
                        sl_price, 
                        "STOPMARKET", 
                        "SELL", 
                        "MIS")

Is it right? Today after placing SL, i got sl_order_Status as “REJECTED”. Log entry-
2025-03-18 10:03:09,416 - WARNING - SL Order status - REJECTED

The reason, I saw was sometihng like this- EXCH:16052:Function Not Available
These are ORder_Details-

{'dhanClientId': '1100000xxx', 'orderId': '62250318144501', 'exchangeOrderId': '1000000036378726', 'correlationId': '1102350080-1742272386271', 'orderStatus': 'REJECTED', 'transactionType': 'SELL', 'exchangeSegment': 'NSE_FNO', 'productType': 'INTRADAY', 'orderType': 'STOP_LOSS_MARKET', 'validity': 'DAY', 'tradingSymbol': 'NIFTY-Mar2025-22750-CE', 'securityId': '50205', 'quantity': 75, 'disclosedQuantity': 0, 'price': 0.0, 'triggerPrice': 88.68, 'afterMarketOrder': False, 'boProfitValue': 0.0, 'boStopLossValue': 0.0, 'legName': 'NA', 'createTime': '2025-03-18 10:03:06', 'updateTime': '2025-03-18 10:03:06', 'exchangeTime': '1980-01-01 00:00:00', 'drvExpiryDate': '2025-03-20', 'drvOptionType': 'CALL', 'drvStrikePrice': 22750.0, 'omsErrorCode': '16052', '**omsErrorDescription': 'EXCH:16052:Function Not Available**', 'algoId': '0', 'remainingQuantity': 75, 'averageTradedPrice': 0.0, 'filledQty': 0}

pls guide me…when googled, I cam to know “STOPMARKET” order is not allowed, instead I hv to use “STOPLIMIT” I am placing this for Options… So, is it right? Also while placing STOPLIMIT,what code should be used…

Hi @saurabha213 ,

Yes, you can update the excel at a time.

1 Like

Hi @Shaurya_Kamdar ,

The code seems to be working fine. Manually try to fetch historical data for any stock or Index and confirm if it is working fine.

Hi @anandc ,

Yes STOPMARKET order is not allowed. You can place STOPLIMIT orders using the below code:

 orderid = tsl.order_placement(tradingsymbol='NIFTY 19 DEC 23300 CALL', exchange='NFO', quantity=75, price=200, trigger_price=205, order_type='STOPLIMIT', transaction_type='BUY', trade_type='MIS')
  • order_id (str): The unique ID of the order to be modified.
  • order_type (str): Type of the order. Options include: - ‘LIMIT’: Limit order. - ‘MARKET’: Market order. - ‘STOPLIMIT’: Stop-loss limit order. - ‘STOPMARKET’: Stop-loss market order.
  • quantity (int): The updated quantity for the order.
  • price (float, optional): The updated price for the order (default is 0).
  • trigger_price (float, optional): The updated trigger price for the order (default is 0).
1 Like

Hi Algo Traders,

Please check this interesting post made by @RahulDeshpande about High Frequency Algo Trades. As a Algo trader we should be able to aware about such things going around and should manage our Algo accordingly to avoid extra penalties or unnecessary charges.

1 Like

Hi Sir,
Can we place AMO orders using Algo?
Kindly guide.

Code runs half way and then I get the following message

C:\Users\Ajay Singh Rajput\Downloads\6. Session6- 1st Live Algo\6. Session6- 1st Live Algo\1st live Algo>py "Screener 1.py"
Codebase Version 3
-----Logged into Dhan-----
reading existing file all_instrument 2025-03-18.csv
Got the instrument file
HDFCBANK is in uptrend
TRENT is in uptrend
AXISBANK is in uptrend
ADANIPORTS is in uptrend
GRASIM is in uptrend
TATASTEEL is in uptrend
LT is in uptrend
Check the Tradingsymbol or Exchange
Traceback (most recent call last):
  File "C:\Users\Ajay Singh Rajput\AppData\Local\Programs\Python\Python38\lib\site-packages\Dhan_Tradehull\Dhan_Tradehull.py", line 504, in get_intraday_data
    raise Exception("Check the Tradingsymbol or Exchange")
Exception: Check the Tradingsymbol or Exchange
Traceback (most recent call last):
  File "Screener 1.py", line 17, in <module>
    chart['rsi'] = talib.RSI(chart['close'], timeperiod=14)
TypeError: 'NoneType' object is not subscriptable