Learn Algo Trading with Python | Codes | Youtube Series

Hi @Tradehull_Imran,

I was testing Live Market feed code, but noticed that it doesn’t give 5min volume data which I need:

{'type': 'Full Data', 'exchange_segment': 1, 'security_id': 1336, 'LTP': '561.60', 'LTQ': 1, 'LTT': '13:25:23', 'avg_price': '550.79', 'volume': 31136096, 'total_sell_quantity': 894856, 'total_buy_quantity': 1411544, 'OI': 0, 'oi_day_high': 0, 'oi_day_low': 0, 'open': '505.10', 'close': '500.55', 'high': '569.45', 'low': '500.50', 'depth': [{'bid_quantity': 8, 'ask_quantity': 290, 'bid_orders': 2, 'ask_orders': 4, 'bid_price': '561.60', 'ask_price': '561.75'}, {'bid_quantity': 635, 'ask_quantity': 14, 'bid_orders': 3, 'ask_orders': 2, 'bid_price': '561.50', 'ask_price': '561.85'}, {'bid_quantity': 19, 'ask_quantity': 305, 'bid_orders': 1, 'ask_orders': 2, 'bid_price': '561.45', 'ask_price': '561.90'}, {'bid_quantity': 608, 'ask_quantity': 557, 'bid_orders': 4, 'ask_orders': 3, 'bid_price': '561.40', 'ask_price': '561.95'}, {'bid_quantity': 327, 'ask_quantity': 4408, 'bid_orders': 3, 'ask_orders': 6, 'bid_price': '561.35', 'ask_price': '562.00'}]}

it’s providing overall volume, is there a way to get the 5min volume without hitting the rate limit or by using any other method.

Hi @VISHWANATH_YERRAMSET

This issue would be there if we are trying to get LTP by webscoket, however we have now upgraded

see : Learn Algo Trading with Python | Codes | Youtube Series - #952 by Tradehull_Imran

also use this sequence for practice : Learn Algo Trading with Python | Codes | Youtube Series - #1065 by Tradehull_Imran

Done @Tradehull_Imran

Hi @Qaisar

There is some issue in options step value, we are checking on it
will release updated code for for it

1 Like

Hi @everyone @kristrades99 @vinay_kumaar @Aijaz_Ahmad

For any rate limit issues, use this new file for Dhan_Tradehull_V2
delete the previous Dhan_Tradehull_V2, and replace it with new one
Filelink : Dhan_Tradehull_V2.py - Google Drive

this line show show up, while running the code

Do run the algo for complete day, and see if you face any issue related to rate limit
Also if the issue is fixed using this file, do let me know, I will mark this post as the answer to rate limit issues

Hi @kristrades99

we needed to put sleep in exit function also

	# ---------------------------- check for exit SL/TG-----------------------------
    # time.sleep(60)
    if traded == "yes":
        long_position  = trade_info['CE_PE'] == "CE"
        short_position = trade_info['CE_PE'] == "PE"
        
        if long_position:
            stop_loss_hit = index_ltp < trade_info['sl']
            target_hit = index_ltp < running_candle['SUPERT_10_2.0']

            if stop_loss_hit or target_hit:
                # call_exit_orderid        = tsl.order_placement(trade_info['options_name'],'NFO', trade_info['qty'], 0, 0, 'MARKET', 'SELL', 'MIS')
                if stop_loss_hit:
                    trade_info['exit_reason']   = 'SL Hit'
                else:
                    trade_info['exit_reason']   = 'Target Hit'
                time.sleep(2)
                trade_info['sell_price']   = tsl.get_ltp_data(names = [ce_name])[ce_name]
                trade_info['exit_time']  = datetime.datetime.now()
                print("Order Exited", trade_info)
                traded = "no"
                # pdb.set_trace()

however, tomorrow test again with this update file Dhan_Tradehull_V2.py - Google Drive

Hi Sir,
kya ye sahi code hai please check and update

rc = index_chart.iloc[-1] #pandas Runing candle
bc = index_chart.iloc[-2] #pandas Breakout candle
ic = index_chart.iloc[-3] #pandas insid candle
ba_c = index_chart.iloc[-4] #pandas Base candle

    print(index_chart)

        # ------------------------- LEVELS----------------------------------------------------
    index_chart1  = {
                    "level1": 24729,
                    "level2": 24646,
                    "level3": 24567,
                    "level4": 24492,
                    "level5": 24437,
                    "level6": 24381,
                    "level7": 24304
                    
                    }
    
    # ----------------------------------BUY-------------------------------------------
    breakout_levels = []

    for level_name, level_value in index_chart1.items():

        if (ba_c['close'] > level_value):
            breakout_levels.append(f"Above {level_name} ({level_value})")

        if any("Above" in level for level in breakout_levels) and (index_chart['rsi'] > 55).any() and ba_c['close'] > ic['close']:
            
                                
                print("buy")

     # ----------------------------------SELL-------------------------------------------    
        if (ba_c['close'] < level_value):
            breakout_levels.append(f"Below {level_name} ({level_value})")
        

        if any("Below" in level for level in breakout_levels) and (index_chart['rsi'] < 50).any() and ba_c['close'] < ic['close']:
                
                    print("sell")


    pdb.set_trace()
    # Display breakout levels
    print("Breakout Levels:")
    for breakout in breakout_levels:
        print(breakout)

hi @Tradehull_Imran sir,
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 1point in our favor 1point sl up

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()}")

Hi @Himansshu_Joshi
I will need to check this question in detail, will resume on the question after todays session

Hi @everyone

live webinar for next topics- Functions and QnA will be conducted on
https://www.youtube.com/@DhanHQ

we will be taking live questions as well, @8pm today.

Also lets discuss regarding rate limits also

4 Likes

@aanand1008 @Abhishek_Konda @Aijaz_Ahmad @arko_seal @arpan_shah @avinashkumar07412 @CBrid @ddeogharkar @francis_antony @Gautam_Singh_Pawar

1 Like

@himansshu_joshi @Hitesh_Maurya @jain79 @Jyothi_Chilukoti @Kalpeshh_Patel @Khandu_Kshirsagar @Kishore007 @kristrades99 @Kuldeep_Khaladkar @Manish_Goel

@Md_Naquibuddin @Milind_Khobragade @pratik_patil2 @Priyesh_Sharma @Qaisar @rahulcse56 @ramakriishna @renuka_mehta @Samis @Siddhesh_Amrute

@Subhajitpanja @thakurmhn @vasili_prasad @Vijen_Singh @vinay_kumaar @vishwanath_yerramset @Zee2Zahid

Hi Team,

We will be conducting our first webinar with @Tradehull_Imran today on our youtube channel.

Time: 8 PM.

We will be taking live QnA and Imran would also be walking us through his first live algo.

2 Likes

Super

hi@tradehull Imran,

“Imran sir, could you please send a algo code for implementing a trailing stop-loss based on the close of the 5-minute VWAP in a bullish trend?”

Sir , Is it

Dhan_websocket_v2

OR

Dhan_Tradehull_v2

Please reconfirm sir. I am confused!

VBR Prasad

Sir, Is it the same updated file Dt.30/10/2024??

OR

Updated just in recent days sir?

(Dhan_tradehull_v2 File)

VBR Prasad

2-Candle Theory: The Ultimate Trading Algorithm || @DhanHQ @OptionsScalping

Today I was reading this one. Probably tomorrow I will do the practical.
But One question I have

When triggering a trade from code not executed due to insufficient balance. However, we are still considering it as a trade. There are many reasons why a trade can be triggered by the code but subsequently fail in the trading panel (e.g., balance issues, liquidity problems, or glitches). If there is a Dhan API that confirms a trade executed successfully, along with other information, then proceed with other processes like Stop Loss, Target, etc. I think that will be good.

Just sharing my thoughts with you, with respect. @Tradehull_Imran sir

and Episode 9 and Episode 10 I will complete as soon as possible

1 Like