Learn Algo Trading with Python | Codes | Youtube Series

Hi @pratik_patil2

  1. This error is related to dhanhq version
  2. This can be covered in commodity market

solution to both of the issues, will be covered in upcoming video release for Dhan_Tradehull_V2.py

1 Like

@Tradehull_Imran
Thanks for quick response :slight_smile: when we will get next video?

Hi @Vijen_Singh

see session3 codebase

  1. exit_all = tsl.cancel_all_orders()

  2. tsl.get_option_chain(symbol, exchange)
    do raise this feature request for this function on below link,
    for all options chain related features I am tracking on this link :
    https://private-poc.madefortrade.in/t/tick-by-tick-algo-for-option-chain-with-oi-buildup-and-covering/34867?u=tradehull_imran

  3. use ce_name, pe_name, strike = tsl.ATM_Strike_Selection('NIFTY','expiry_date')

  4. live_pnl = tsl.get_live_pnl()

  1. exit_all = tsl.cancel_all_orders()
    isse to jo order hai wo cancel honge na position bhi exit ho jayegi kya?

    1. use ce_name, pe_name, strike = tsl.ATM_Strike_Selection('NIFTY','expiry_date')

mujhe ATM, OTM ya ITM ki strick price nhi chahiye mujhe premium based strick price chahiye qki mujhe pta hi nhi hai 95 greater than premium kisme aayega OTM me aayega ya ITM me ya ATM me

to me 1. use ce_name, pe_name, strike = tsl.ATM_Strike_Selection('NIFTY','expiry_date')
is function ka use kese kru?

Thanks for the response but message is not going to telegram… may be i am not doing the right thing…

Also i am not able to place target order as we well. please help
target_order = tsl.order_placement(stock_name,‘NSE’, qty, 0, target_price,‘LIMIT’, ‘BUY’, ‘MIS’)

Hi Sir @Tradehull_Imran ! Thank you so much for the prompt response . Power shell method worked . I’m getting the LTPs now. No more SSL erros

However, on running the codebase file, I’m unable to fetch balance. I haven’t changed the code . I’ve just used pdb.set_trace (). I’m getting the error that : “Error at Gettting balance as string indices must be integers
available_balance 0”. Please help.

@Tradehull_Imran Sir, Thanks for the resolution of websocket errors. I’m able to fetch the LTPs now.

Hi everyone,

Below is the explanation video for Dhan_Tradehull_V2
This will solve majority of the issues you were facing in LTP and Historical data as well.

Codefiles : https://drive.google.com/file/d/1wCN8zpwHNKyW0xws9jhUMrkQVj5ehBRU

9 Likes
import pdb
from Dhan_Tradehull import Tradehull
import pandas as pd
import talib
import time

# Trading API client setup
client_code = ""
token_id = ""
tsl = Tradehull(client_code, token_id)

# Intraday strategy parameters
available_balance = tsl.get_balance()
leveraged_margin = available_balance * 5  # 5x leverage
max_trades = 1
per_trade_margin = leveraged_margin / max_trades  # Amount for each trade

# Watchlist
watchlist = ['NBCC', 'RVNL', 'IFCI', 'HUDCO', 'MAZDOCK', 'INOXWIND', 'ZEEL', 'BSE', 'MMTC', 'ITI', 'BEML', 'SUZLON', 'HINDCOPPER', 'RELIANCE']
traded_watchlist = []

# Function to calculate 69 EMA and check for trend (uptrend/downtrend)
def check_trend_and_touch_ema(chart):
    # Calculate 69 EMA for the chart
    chart['69ema'] = talib.EMA(chart['close'], timeperiod=69)
    
    # Get the last 4 EMA values for slope detection
    ema_values = chart['69ema'].iloc[-4:].values  # Last 4 EMA values
    ema_slope_uptrend = all(ema_values[i] < ema_values[i+1] for i in range(3))  # Uptrend condition
    ema_slope_downtrend = all(ema_values[i] > ema_values[i+1] for i in range(3))  # Downtrend condition

    # Get the most recent candle (breakout candle)
    bc = chart.iloc[-2]  # Breakout candle

    # Check if any part of the candle touches the 69 EMA (either body or wick)
    touch_ema_uptrend = (bc['high'] >= bc['69ema'] >= bc['low']) or (bc['close'] >= bc['69ema'] >= bc['open'])
    touch_ema_downtrend = (bc['high'] >= bc['69ema'] >= bc['low']) or (bc['close'] <= bc['69ema'] <= bc['open'])

    return ema_slope_uptrend, ema_slope_downtrend, touch_ema_uptrend, touch_ema_downtrend, bc

# Main loop for the strategy
while True:
    for stock_name in watchlist:
        print(f"Processing {stock_name}…")
        
        # Fetch intraday data for the stock (1-minute candles)
        chart = tsl.get_intraday_data(stock_name, 'NSE', 15)  # Fetch 1-minute candles
        if chart is None or chart.empty:
            print(f"No data retrieved for {stock_name}. Skipping...")
            continue
        
        # Check trend and EMA touch conditions
        try:
            ema_slope_uptrend, ema_slope_downtrend, touch_ema_uptrend, touch_ema_downtrend, bc = check_trend_and_touch_ema(chart)
            print(f"{stock_name} - 69 EMA values: {chart['69ema'].iloc[-4:]}")
            print(f"Uptrend: {ema_slope_uptrend}, Downtrend: {ema_slope_downtrend}")
            print(f"Touch EMA Uptrend: {touch_ema_uptrend}, Touch EMA Downtrend: {touch_ema_downtrend}")
        except Exception as e:
            print(f"Error processing {stock_name}: {e}")
            continue
        
        # Ensure there is enough data for trend analysis
        if len(chart) < 4:
            print(f"Not enough data for {stock_name}. Skipping...")
            continue

        # Check for trade conditions
        no_repeat_order = stock_name not in traded_watchlist
        max_order_limit = len(traded_watchlist) < max_trades  # Ensure we don't exceed max trades

        # Calculate quantity to trade based on the available margin
        qty = int(per_trade_margin / bc['close'])  # Quantity based on the price of the stock

# Assuming you already have the correct logic in place for determining uptrend/downtrend
# and the other conditions for placing orders.

        # Example when placing a sell order (if conditions for downtrend and touch EMA are met)
        if ema_slope_downtrend and touch_ema_downtrend and no_repeat_order and max_order_limit:
            print(f"Placing sell order for {stock_name} - Quantity: {qty}")
            trigger_price = 0  # For a market order, trigger price might not be needed
            tsl.order_placement(stock_name, 'NSE', qty, 1, 0, 'MARKET', 'BUY', 'MIS')
            traded_watchlist.append(stock_name)
            time.sleep(10)  # Sleep to prevent hitting API rate limits

        # Example when placing a buy order (if conditions for uptrend and touch EMA are met)
        if ema_slope_uptrend and touch_ema_uptrend and no_repeat_order and max_order_limit:
            print(f"Placing buy order for {stock_name} - Quantity: {qty}")
            trigger_price = 0  # For a market order, trigger price might not be needed
            tsl.order_placement(stock_name, 'NSE', qty, 1, 0, 'MARKET', 'SELL', 'MIS')
            traded_watchlist.append(stock_name)
            time.sleep(10)  # Sleep to prevent hitting API rate limits

    time.sleep(10)  # Sleep between each watchlist check

When keep the tsl.get_intraday_data(stock_name, ‘NSE’, 1) to 1 minute the order gets place instantly but if I make it to 15 min then the order is not getting placed at all. Not sure what the issue is here.
This is a different strategy I was trying by seeing the upward/downward trend candle of 15 min timeframe touching the 69 EMA line to place orders.

Also I haven’t been able to figure out how to place stop loss and targets to my orders. I am doing it manually now. I would want it to be automated through the code. Could you please help with this.

Hi Sir!
In the file " " , when I enter my dhan credentials , I get the attached error. However , if I’m running the file with already entered credentials, code is running fine. Please help resolve the issue.

File name “1. Easy way to get LTP.py”

Finally

3 Likes

Waow

1 Like

Hye @Tradehull_Imran

Big Thankyou for such an informative video, now please guide us how to deploy it in server, because keeping laptop on all the time is not possible for strategy execution.

2 Likes

Very informative

1 Like

Totally agree @Zee2Zahid :+1:

Already requested to @Tradehull_Imran sir from my side also

how to write supertrend indicator in talib format?

1 Like


Hye @Tradehull_Imran

I am unable to get ltp of Put options, Using Tradehull_v2

@Tradehull_Imran hi sir mene youtube pr session 8 dekha usse mene code copy

wait for market to start 09:29:58.468498
wait for market to start 09:29:59.547835
MOTHERSON
dhanhq.intraday_minute_data() takes 4 positional arguments but 7 were given
Traceback (most recent call last):
File “/Users/vijju/Desktop/Stock Algo/Dhan Algo/8. Session8- 2nd Live Algo/2nd live Algo/Dhan_Tradehull_V2.py”, line 257, in get_historical_data
ohlc = self.Dhan.intraday_minute_data(str(security_id),exchange_segment,instrument_type,self.start_date,self.end_date,int(interval))
TypeError: dhanhq.intraday_minute_data() takes 4 positional arguments but 7 were given
Traceback (most recent call last):
File “/Users/vijju/Desktop/Stock Algo/Dhan Algo/8. Session8- 2nd Live Algo/2nd live Algo/Multi timeframe Algo.py”, line 58, in
chart_1[‘rsi’] = talib.RSI(chart_1[‘close’], timeperiod=14) #pandas
TypeError: ‘NoneType’ object is not subscriptable
vijjus-MacBook-Air:8. Session8- 2nd Live Algo vijju$

ye error aa rhi hai

TA-Lib

Notion

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

client_code = “1101529493”
token_id = “eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJkaGFuIiwicGFydG5lcklkIjoiIiwiZXhwIjoxNzMxNzcxMDU4LCJ0b2tlbkNvbnN1bWVyVHlwZSI6IlNFTEYiLCJ3ZWJob29rVXJsIjoiIiwiZGhhbkNsaWVudElkIjoiMTEwMTUyOTQ5MyJ9.Oo3_dwF1lGkiSenKu-XdpsMZIav5og-BK2CxzuTPyaAZGyUMDJEb_lCaTOLXwydfeeXbwzeKRs3pHXhlosKGGQ”
tsl = Tradehull(client_code,token_id) # tradehull_support_library

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

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’]

watchlist = [‘CRUDEOIL’]

traded_wathclist =

while True:

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

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


if (current_time > datetime.time(15, 15)) 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.2)
	print(stock_name)



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


	chart_1['rsi'] = talib.RSI(chart_1['close'], timeperiod=14) #pandas
	cc_1           = chart_1.iloc[-2]  #pandas  completed candle of 1 min timeframe
	uptrend        = cc_1['rsi'] > 50
	# downtrend      = cc_1['rsi'] < 49


	# 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 ub_breakout and no_repeat_order and max_order_limit:
		print(stock_name, "is in uptrend, Buy this script")

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

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

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

	# 	sl_price          = round((cc_1['close']*1.02),1)
	# 	qty               = int(per_trade_margin/cc_1['close'])

	# 	buy_entry_orderid = tsl.order_placement(stock_name,'NSE', 1, 0, 0, 'MARKET', 'SELL', 'MIS')
	# 	sl_orderid        = tsl.order_placement(stock_name,'NSE', 1, 0, sl_price, 'STOPMARKET', 'BUY', 'MIS')
	# 	traded_wathclist.append(stock_name)

ye code hai please help me

1 Like

Hi @Tradehull_Imran,

Thanks for the updated API… I am able to extract historical data in 1 min and 5 min interval… can i get intraday historical data in 2 min tf ?

trying to get 2 min interval historical data and got the below error
data_day = tsl.get_historical_data(tradingsymbol = ‘ACC’,exchange = ‘NSE’,timeframe=“2”)

ValueError: DataFrame constructor not properly called!

Thanks in advance