Tomorrow, we will study functions and live QnA.
Share the link for live session, please.
Hi Sir, i have been trying AMO order but doesn’t look like dhan supports AMO order.
following are the Product type allowed as per the Dhan doc(Orders - DhanHQ Ver 2.0 / API Document)
CNC
INTRADAY
MARGIN
MTF
CO
BO
My Code:
buy_entry_orderid = tsl.order_placement(stock_name,'NSE', 1, 0, 0, 'MARKET', 'BUY', 'AMO')
Error:
KeyError: 'orderId'
Traceback (most recent call last):
File "d:\WORK\dhan-algo\Dhan_Tradehull.py", line 139, in order_placement
orderid = order["data"]["orderId"]
these are the allowed product type in tradehull also, as AMO is not listed here we are getting above error
product = {'MIS':self.Dhan.INTRA, 'MARGIN':self.Dhan.MARGIN, 'MTF':self.Dhan.MTF, 'CO':self.Dhan.CO,'BO':self.Dhan.BO, 'CNC': self.Dhan.CNC}
Very good Morning Sir,
We are slow in catching-up as people like me, non-coders, request you to keep the “MadeForTrade” platform open for pretty long time, till we non-coders catchup with the coding nuances, thoroughly if not perfectly, making us eligible to use for trading purposes.
I also suggest and request to finally release a folder containing all proven files like: codebase, dhan_tradehull_2 or latest vesrions, websocket files etc.,
Hope Dhan Team will support us sir.
Thank you veery much Imran Sir, for all your sincere approach and guidelines to all participants.
Thanks Again.
WE do welcome the proven code snippets by Participants to be included in the Final Folder sir, voluntarily with no inhibitions.
VBR Prasad
Hello @Tradehull_Imran
Sir, I ve created an Intraday Scanner for NIFTY200 stocks, It scans 200 stocks in about 3-4 minutes, It it possible to increase API HI rate or speed so as to get the results in less than a minute.
Thank You
Sometimes these codes work, & sometimes dosent, there is some issue with tradehull codebase or dhan api in prividing data.
yesterday practicing EP-09 - 3rd live algo, it was working just fine but today the same code not providing ATM strikes & giving error for stocks like TCS, SBIN & LT
Nifty_T10_watchlist = [‘TCS’, ‘LT’, ‘BHARTIARTL’, ‘SBIN’]
for stock_name in Nifty_T10_watchlist:
print(stock_name)
ATM_CE, ATM_PE, ATM_Strike = tsl.ATM_Strike_Selection(stock_name, '26-12-2024')
print(ATM_CE, "_____", ATM_PE)
ERROR -
Codebase Version 2.1
-----Logged into Dhan-----
reading existing file all_instrument 2024-12-04.csv
Got the instrument file
TCS
Traceback (most recent call last):
File “D:\Dhan Algo\Practice\Dhan_Tradehull_V2.py”, line 514, in ATM_Strike_Selection
closest_index = ce_df[‘diff’].idxmin()
File “C:\Users\lenovo\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\series.py”, line 2460, in idxmin
i = self.argmin(axis, skipna, *args, **kwargs) # type: ignore[arg-type]
File “C:\Users\lenovo\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\base.py”, line 742, in argmin
return nanops.nanargmin( # type: ignore[return-value]
File “C:\Users\lenovo\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\nanops.py”, line 96, in _f
return f(*args, **kwargs)
File “C:\Users\lenovo\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\nanops.py”, line 1193, in nanargmin
result = values.argmin(axis) # type: ignore[var-annotated]
ValueError: attempt to get argmin of an empty sequence
— Logging error —
Traceback (most recent call last):
File “D:\Dhan Algo\Practice\Dhan_Tradehull_V2.py”, line 514, in ATM_Strike_Selection
closest_index = ce_df[‘diff’].idxmin()
File “C:\Users\lenovo\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\series.py”, line 2460, in idxmin
i = self.argmin(axis, skipna, *args, **kwargs) # type: ignore[arg-type]
File “C:\Users\lenovo\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\base.py”, line 742, in argmin
return nanops.nanargmin( # type: ignore[return-value]
File “C:\Users\lenovo\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\nanops.py”, line 96, in _f
return f(*args, **kwargs)
File “C:\Users\lenovo\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\nanops.py”, line 1193, in nanargmin
result = values.argmin(axis) # type: ignore[var-annotated]
ValueError: attempt to get argmin of an empty sequence
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File “C:\Users\lenovo\AppData\Local\Programs\Python\Python38\lib\logging_init_.py”, line 1081, in emit
msg = self.format(record)
File “C:\Users\lenovo\AppData\Local\Programs\Python\Python38\lib\logging_init_.py”, line 925, in format
return fmt.format(record)
File “C:\Users\lenovo\AppData\Local\Programs\Python\Python38\lib\logging_init_.py”, line 664, in format
record.message = record.getMessage()
File “C:\Users\lenovo\AppData\Local\Programs\Python\Python38\lib\logging_init_.py”, line 369, in getMessage
msg = msg % self.args
TypeError: not all arguments converted during string formatting
Call stack:
File “test.py”, line 24, in
ATM_CE, ATM_PE, ATM_Strike = tsl.ATM_Strike_Selection(stock_name, ‘26-12-2024’)
File “D:\Dhan Algo\Practice\Dhan_Tradehull_V2.py”, line 541, in ATM_Strike_Selection
self.logger.exception("Got exception in ce_pe_option_df ", e)
Message: 'Got exception in ce_pe_option_df ’
Arguments: (ValueError(‘attempt to get argmin of an empty sequence’),)
exception got in ce_pe_option_df attempt to get argmin of an empty sequence
None _____ None
How can we put our money with these type of codes which sometimes work & sometimes same codes doesnt
Hi @Arpan_Shah
yes codes for session are fine, however do increase time.sleep() to 3 seconds, to manage rate limits
Hi @vinay_kumaar
This is a rate limit issue
See : Learn Algo Trading with Python | Codes | Youtube Series - #860 by Tradehull_Imran
hi @Tradehull_Imran sir,
trading_symbol = "NIFTY 05 DEC 24400 CALL" # Example stock symbol
qty = 125 # Example quantity
buying_trigger = 205.3 # Lower
buying_limit_price = buying_trigger + 0.50 # Higher
stop_loss_offset = 181.4 # Example stop-loss offset
target_offset = 33 # Example target price
exchange = "NFO"
ordertype = "STOPLIMIT"
# Initialize Tradehull
tsl = Tradehull(client_code, token_id)
try:
# Place buy order
buy_entry_orderid = tsl.order_placement(trading_symbol, exchange, qty, buying_limit_price, buying_trigger, ordertype, 'BUY', 'MIS')
print(f"Buy Order Placed. Order ID: {buy_entry_orderid}")
time.sleep(0.2)
while True:
try:
# Fetch order details and status
order_details = tsl.get_order_detail(orderid=buy_entry_orderid)
order_status = tsl.get_order_status(orderid=buy_entry_orderid)
print(f"Order Status: {order_status}")
time.sleep(1)
# Check for pending status and cancel order if stop_loss_offset is breached
if order_status == "PENDING":
current_market_price_dict = tsl.get_ltp_data(names=[trading_symbol])
current_market_price = current_market_price_dict[trading_symbol]
if current_market_price <= stop_loss_offset:
print(f"Market price {current_market_price} is below stop-loss offset {stop_loss_offset}. Canceling order.")
tsl.Dhan.cancel_order(buy_entry_orderid)
print(f"Order {buy_entry_orderid} canceled. Stopping algorithm.")
break # Exit the main loop and stop the algorithm
if order_status == "TRADED":
buy_price = order_details['price']
target_price = buy_price + target_offset
stop_loss_price = stop_loss_offset
sl_limit_price = stop_loss_price - 1
# Place stop-loss order
stoploss_orderid = tsl.order_placement(trading_symbol, exchange, qty, sl_limit_price, stop_loss_price, 'STOPLIMIT', 'SELL', 'MIS')
print(f"Stop Loss Order Placed. Order ID: {stoploss_orderid}")
time.sleep(0.2)
# Monitor for target price
while True:
try:
current_market_price_dict = tsl.get_ltp_data(names=[trading_symbol])
current_market_price = current_market_price_dict[trading_symbol]
if current_market_price >= target_price:
# Cancel stop-loss order
tsl.Dhan.cancel_order(stoploss_orderid)
print(f"Stop Loss Order {stoploss_orderid} canceled.")
# Place sell order
sell_entry_orderid = tsl.order_placement(trading_symbol, exchange, qty, 0, 0, 'MARKET', 'SELL', 'MIS')
print(f"Target reached. Selling {trading_symbol} at market price. Sell Order ID: {sell_entry_orderid}")
break
else:
print(f"Buy Price: {buy_price}, Current Price: {current_market_price}, Target: {target_price}")
time.sleep(0.2) # Adjust sleep interval if necessary
except Exception as e:
print(f"Error in monitoring target: {traceback.format_exc()}")
time.sleep(0.2)
break
except Exception as e:
print(f"Error in fetching order details or status: {traceback.format_exc()}")
time.sleep(0.2)
except Exception as e:
print(f"Unexpected error: {traceback.format_exc()}")
so how i can trail sl please give exact change that i need to do. i want trailing sl in 2 ways,
1: if points reach 20 so it should be ctc sl ,
2: normal way it point in our favour 1point sl up
Which CPU are you using to run the code ?
Also there may be some issue in Virtual env, try reinstalling it
Also now Dhan_Tradehull has been upgraded to Dhan_Tradehull_V2,
see : Learn Algo Trading with Python | Codes | Youtube Series - #952 by Tradehull_Imran
Also do check this sequence : Learn Algo Trading with Python | Codes | Youtube Series - #1065 by Tradehull_Imran
Hi @Tradehull_Imran, @Hardik
I tested the code again today with a new api_key and also deleted the earlier keys. I introduced additional 30 second sleep inside the main while loop. However, I’m still getting the same errors. Error1 is due to some rate limit issue…Not sure why Error2 is happening… Its become quite a mystery for me to solve
1. data': {'805': 'Too many requests. Further requests may result in the user being blocked.'}
2. File "C:\Users/krish/DhanAlgoTrading/Required Files\Dhan_Tradehull_V2.py", line 546, in ATM_Strike_Selection
self.logger.exception("Got exception in ce_pe_option_df ", e)
Message: 'Got exception in ce_pe_option_df '
Arguments: (KeyError('NIFTY'),)
send the drive link of the complete folder,
will check the code again
Hi @Renuka_Mehta
The installation is complete now,
do check this video sequence for further progress : Learn Algo Trading with Python | Codes | Youtube Series - #1065 by Tradehull_Imran
Link for latest codebase / Dhan_Tradehull_V2.
Also do practice the Algo in below sequence
Raising Feature request for increasing rate limits
Adding @Hardik for same,
@Tradehull_Imran
HI Imran,
I am getting error , while running Dhan_websocket.py file. Please let this solve.
"Microsoft Windows [Version 10.0.19045.5198]
(c) Microsoft Corporation. All rights reserved.
D:\Dhan_algo\3. Session3 - Codebase\Dhan codebase>py Dhan_websocket.py
Reading existing file all_instrument 2024-12-04.csv
Watchlist changed. Reconnecting the feed…
Disconnected from WebSocket feed.
WebSocket connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108)
Reconnecting Again…"
Hi @Tradehull_Imran, Below is the GDrive link
@Tradehull_Imran, I am using Pentium E5700 processor,
and I’ll do as you suggested and let you know.
do share the access to tradehull_mentorship@tradehull.com