Learn Algo Trading with Python | Codes | Youtube Series

I think there is no need to use websocket anymore.

Dhan_Tradehull_v2 will get the LTP & historical data

1 Like

Hi everyone,

Since now we have reached the level for basic algo trading,
we can start replying to each other

This way answer response time on madefortrade will also be less…
we all will get answers much quicker.

2 Likes

Same question from me also, as tradehull is taking data from instrument file, then what is the use of websocket file? I believe definitely there must be a better reason to use websocket which we are missing. will using websocket will reduce the number of call we are making per 1 minute for example to get 1 minute data for any instrument ?

@Tradehull_Imran please help us understand what we are missing here?

To find the solution play this video from 55:15 mins @ Vasili_Prasad @ arko_seal

@Tradehull_Imran sir explained here

1 Like

Websocket is a Older Version and in Upgraded version of Code Base , we Dont want Websocket for getting LTP, Trust me I am Following @Tradehull_Imran from the beginning Websocket is very tedious process to get LTP,

as Per Rate Limit concern , It has also been Upgraded , Please Check this Post. https://madefortrade.in/t/learn-algo-trading-with-python-codes-youtube-series/32718/1330?u=kishore007

Kudos to Dhan and Imran, Sir for Updating the Code Base.

4 Likes

@Tradehull_Imran , Sir…

Please Share Live Webinar Folder, Sir…

Thank you for sharing Your knowledge and Experience with us , Sir…!

1 Like

Hello @Tradehull_Imran,

Live algo is executing seamlessly… thanks for guidance… please schedule the back testing session ASAP…

Thanks,
Rahul


2 Likes

Its Dhan_Tradehull_V2. The websocket version was the old way of doing things where an excel sheet was required to get the LTP data. In Dhan_Tradehull_V2 that has been changed and you can get the LTP directly through a function call

1 Like

Hello @Vasili_Prasad

I would suggest you to go through each and every comments of this tread… your queries will be solved automatically. in case you are facing some issues then we are here to help you.

-Rahul

2 Likes

Let me know if anyone is facing rate limit issue after implementing this post

Sir can we get option chain using data api?

As of now, Its running fine, sir…

Thank you for this update, sir

1 Like

Hi @Tradehull_Imran,

I am testing and will update you, in mean time can you please suggest if we have 300 - 400 stocks for which OHLCV data needs to be pulled every 3-5min how should we implement this.

Hi @SUKANTA_MONDAL

use below code reference

	# ---------------------------- check for exit SL/TG

	if traded == "yes":

		long_position  = trade_info['CE_PE'] == "CE"
		short_position = trade_info['CE_PE'] == "PE"


		if long_position:
			sl_hit = index_ltp < trade_info['sl']
			tg_hit = index_ltp < running_candle['vwap']

			if sl_hit or tg_hit:
				print("Order Exited", trade_info)
				exit_orderid        = tsl.order_placement(trade_info['options_name'],'NFO', trade_info['qty'], 0, 0, 'MARKET', 'SELL', 'MIS')
				pdb.set_trace()

Also for explanation see below video,
in this we have trailed our position according to Supertrend : https://youtu.be/wlQWSLzp_UI?si=6_AH_dv65jflpO9J&t=2989

1 Like

Hi @Subhajitpanja

This is correct, we do need to cross-confirm that the order we have sent is executed or not.
we can do this by checking order status,
use reference code


order_status  = tsl.get_order_status(orderid='give_your_orderid')

if order_status == 'TRADED':
    print("Order is suscessfully executed")


if order_status == 'PENDING':
    print("Order is PENDING")
1 Like

Hi @Kishore007
I will need to clean the code and make it in working condition, will update the same.

1 Like

Hi @Aijaz_Ahmad

Fetching historical data for 300-400 scripts every 5 mins will breach rate limits.
Also there is a method we can make candlestick by from ltp data, but its bit less accurate.

Hi @Tradehull_Imran,

Yes excatly and Dhan websocket provides live or tick by tick OHCL & market depth but doesn’t volume in realtime. Please suggest how to solve such issue

Hi @Himansshu_Joshi

I have added pseudocode for both trailing types.

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

                breakeven_happened = "no"
                initial_sl_price   = stop_loss_price


                # 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)

                while True:

                    try:



                        # Monitor for target price
                        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



                        # 1: if points reach 20 so it should be ctc sl , BREAKEVEN,
                        if (current_market_price > (buy_price + 20)) and (breakeven_happened == "no"):
                            stop_loss_price = buy_price
                            breakeven_happened = "yes"




                        # 2: normal way it 1point in our favor 1point sl up
                        # or we can say, the entry_sl_distace should remain same, this way if current_market_price increase by 1 stop_loss_price will also increase by 1, keeping entry_sl_distace constant
                        entry_sl_distace = (buy_price - initial_sl_price)
                        stop_loss_price  = current_market_price - entry_sl_distace




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




Thank you, I am practicing on this files

1 Like