- This error is related to dhanhq version
- 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
solution to both of the issues, will be covered in upcoming video release for Dhan_Tradehull_V2.py
@Tradehull_Imran
Thanks for quick response
when we will get next video?
Hi @Vijen_Singh
see session3 codebase
exit_all = tsl.cancel_all_orders()
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
use ce_name, pe_name, strike = tsl.ATM_Strike_Selection('NIFTY','expiry_date')
live_pnl = tsl.get_live_pnl()
exit_all = tsl.cancel_all_orders()
isse to jo order hai wo cancel honge na position bhi exit ho jayegi kya?
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
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
Waow
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.
Very informative
Totally agree @Zee2Zahid ![]()
Already requested to @Tradehull_Imran sir from my side also
how to write supertrend indicator in talib format?
@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
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_balance1)/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â]
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
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