Learn Algo Trading with Python | Codes | Youtube Series

Im aware of that if there is no open position it shows 0. But I mean also when it open. But more than this, simple LTP call is also soooo unreliable Imran. Ive been wanting to say this so many times! Yesterday and today too, randomly LTP is not being returned at all, and i dont mean just one or seconds, for like 20-30 mins!! and then again it starts working on after some time. The entire trade setup is gone, it does not exit for the SL or target because its not fetching the LTP itself to exit based on!! in a matter of seconds, by the time you realise the LTp calls is not returning the value, the price has fallen so much. LTP is a basic call. Its not possible to automate trading when its so unreliable. right now even, for like an hour LTP giving empty. same like yesterday. isolated the ltp call sepaartely to check too

Hi @Msk92

There may be a possibility that it may be exceeding rate limits.
I am also checking on the same concept, will update you on this.

@Aijaz_Ahmad hello bro can u share code i am stucked at here , what i am trying, placing order using pyhton (manually inserting order) then i want it to
chase my sl and target if target hit cancel sl order and square off position at market

SIR @Tradehull_Imran , hello i have tried so many times for making my algo works but somehow i stuck some where, can u give any working code where it fetch orderid and modify sl order to market order to make it square off

Hi @Tradehull_Imran,
I’m trying to get the data of specific option strike using get_historical_data function. However It’s throwing up the below error. I tried multiple past and future expiry dates and getting the same error everytime.

Am I using it incorrectly or is there any other issue? Can you pls help

option_data = tsl.get_historical_data(tradingsymbol='NIFTY 5 DEC 24000 CALL',exchange='NFO',timeframe='1')	
print(option_data)

Error

Exception in Getting OHLC data as single positional indexer is out-of-bounds

Hi @kristrades99

NIFTY 5 DEC 24000 CALL, needs to be 0 padded date, like NIFTY 05 DEC 24000 CALL

use below code
tsl.get_historical_data(tradingsymbol='NIFTY 05 DEC 24000 CALL',exchange='NFO',timeframe='1')

1 Like

I am able to place orders but getting below error even after placing sleep(10)

if last_signal_condition and fut_up:
            pc_2 = intraday_df.iloc[-2] # previous candle 
            call_entry_orderid, order_price, qty, ce_name = _place_call_order_gpt()
            traded                     = "yes"
            trade_info['options_name'] = ce_name
            trade_info['qty']          = qty
            trade_info['sl']           = fut_pc['low']
            trade_info['CE_PE']        = "CE"
            trade_info['entry_orderid'] = call_entry_orderid

            time.sleep(10)
            trade_info['entry_price'] = tsl.get_executed_price(orderid=trade_info['entry_orderid'])


2024-11-29 13:00:14,230 - nifty_strategy_test_v2.py - INFO - Placing order for NIFTY 05 DEC 24050 CALL
2024-11-29 13:00:14,323 - nifty_strategy_test_v2.py - ERROR - Error in placing call order: Failed to retrieve executed price for Call order 102241129292229.
Traceback (most recent call last):
File “/home/mohan/Dhan-Alog-Trading/examples/nifty_strategy_test_v2.py”, line 605, in
call_entry_orderid, order_price, qty, ce_name = _place_call_order_gpt()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: cannot unpack non-iterable NoneType object

Nothing. Tested with just one single call via a simple program by passing the call_list parameter and it returns empty. It 1pm noon and still not returning ltp since morning. This has happend sooo many times since the time you guys introduced LTP call. There is a live open position and LTP returns empty, this is crazy to have to automate this way. Please tell me honestly if your APIs are in beta testing or something ? Cannot risk this way. As shown below.

def getLtp(tsl,call_list):

print("getting ltp ...", call_list)
ltp_data = tsl.get_ltp_data(names = call_list)
print(ltp_data)
return ltp_data

getLtp(tsl, call_list)

Output:
-----Logged into Dhan-----
reading existing file all_instrument 2024-11-29.csv
Got the instrument file
getting ltp … [‘NIFTY 05 DEC 24300 PUT’]
NIFTY 05 DEC 24300 PUT
{}

Please Ingnore this.

there was typo error

1 Like

Thanks @Tradehull_Imran. This worked.

Quick followup question - How do I get past expiry data…for example 29 AUG 2024. If i try this date I get the error “Exception in Getting OHLC data as single positional indexer is out-of-bounds”.

Which function needs to be used for getting historical option data?

Hi @kristrades99
Historical options data is not supported as of now in dhnahq.
Although we can raise feature request for it.

adding @Hardik for same.

1 Like

sir new version release.

1 Like

:+1:

Hi @Msk92
I checked the algo codes, by managing rate limits using time.sleep()
The code ran fine with no issues.

Do share the sample code which gave the ltp errors

Hi @Himansshu_Joshi
Will check the same on Monday live market.

thanks sir, and please share the codes also

2-Candle Theory Ko check kar rha hu yhi massege aa rha hai (File “C:\Users\VINAY\Desktop\Smart traders\Dhan code\Dhan_Tradehull_V2.py”, line 140, in order_placement
orderid = order[“data”][“orderId”]
KeyError: ‘orderId’) AMO order change kane ke bad bhi

Hi @Himansshu_Joshi ,

Check this code:

buy_entry_orderid = tsl.order_placement(stock_symbol, 'NSE', qty, 0, 0, 'MARKET', 'BUY', 'MIS')
print(f"Order ID: {buy_entry_orderid}")


    while True:
        try:
            # Get order details
            order_details = tsl.get_order_detail(orderid=buy_entry_orderid)

            # Double check if the order is completed
            order_status = tsl.get_order_status(orderid=buy_entry_orderid)
            print(f"Order status response: {order_status}")

            if order_status == "TRADED":
                buy_price = order_details['price']  # Extract price from order details
                target_price = buy_price + XXX      # Replace XXX with your target number for e.g. replace it with either 5, 10 or 20 etc.

                stoploss_orderid = tsl.order_placement(stock_symbol, 'NSE', qty, 0, stop_loss_price, 'STOPMARKET', 'SELL', 'MIS')
                print(f"Stoploss order ID: {stoploss_orderid}")
                #print("I have double checked: Order Completed")

                while True:
                    try:
                        # Fetch the current market price
                        current_market_price_dict = tsl.get_ltp_data(names=[stock_symbol])
                        current_market_price = current_market_price_dict[stock_symbol]

                        # Check if the current market price has reached or exceeded the target price
                        if current_market_price >= target_price:
                            # Cancel the stop loss order
                            tsl.Dhan.cancel_order(stoploss_orderid)
                            print(f"Stop loss order {stoploss_orderid} canceled.")

                            # Place the sell order
                            sell_entry_orderid = tsl.order_placement(stock_symbol, 'NSE', qty, 0, 0, 'MARKET', 'SELL', 'MIS')
                            print(f"Target reached, selling {stock_symbol} at market price.")
                            print(f"Sell order ID: {sell_entry_orderid}")
                            break
                        else:
                            print(f"Buy price : {buy_price}, Current market price: {current_market_price}, waiting to reach target price: {target_price}")

                        # Sleep for a short interval before checking again
                        time.sleep(0.5)

                    except Exception as e:
                        print(f"An error occurred: {e}")
                        break

                break
1 Like

Hi @Hardik, Kindly consider taking up this feature request. This is already available on Fyers…attached below is the sample code for getting 19th Sep 2024 expiry option prices and the corresponding output (available @1 min interval)

Code

app = FyersApp()
formatted_symbol = app.get_formatted_symbol('NIFTY','INDEX','19/09/2024','25000CE')
pprint(app.get_historical_data(formatted_symbol))

Output

                       Open    High     Low   Close  Volume
Date                                                       
2024-09-02 09:15:00  492.95  492.95  492.95  492.95      25
2024-09-02 09:16:00  492.95  492.95  492.95  492.95       0
2024-09-02 09:17:00  492.95  493.05  492.95  493.05      25
2024-09-02 09:18:00  493.05  497.60  490.90  497.60     175
2024-09-02 09:19:00  497.60  497.60  497.60  497.60       0
...                     ...     ...     ...     ...     ...
2024-09-19 15:25:00  415.35  416.90  415.35  416.40   10250
2024-09-19 15:26:00  415.45  416.85  415.40  415.40    2700
2024-09-19 15:27:00  415.30  416.25  415.20  415.55    5950
2024-09-19 15:28:00  415.55  416.80  415.55  416.00    3900
2024-09-19 15:29:00  416.00  416.40  415.35  416.35    6350

[5247 rows x 5 columns]
1 Like

Hi@ Tradehull_Imran.
respeted sir,
I’m writing to express my sincere appreciation for your exceptional teaching on algorithmic trading. I’m particularly interested in developing strategies for option buying based on bullish and bearish engulfing patterns on a 5-minute timeframe. Additionally, I would be grateful for guidance on implementing a robust trailing stop-loss mechanism.

Thank you for your time and consideration.