Learn Algo Trading with Python | Codes | Youtube Series

(Pdb++) historical_data = tsl.get_historical_data(‘TCS’, ‘NSE’, ‘1’)
unsupported type for timedelta days component: str
Traceback (most recent call last):
File “C:\Users\Ajay Singh Rajput\AppData\Local\Programs\Python\Python38\lib\cmd.py”, line 214, in onecmd
func = getattr(self, ‘do_’ + cmd)
AttributeError: ‘Pdb’ object has no attribute ‘do_historical_data’

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File “C:\Users\Ajay Singh Rajput\Downloads\3. Session3 - Codebase\3. Session3 - Codebase\3. Session3 - Codebase\Dhan codebase\Dhan_Tradehull.py”, line 211, in get_historical_data
from_date= datetime.datetime.now()-datetime.timedelta(days=days)
TypeError: unsupported type for timedelta days component: str
(Pdb++)

Thank you for the revert still getting a error

Hi @Qaisar ,

In option chain full name of strikes are not provided by the API, you may need to explicitly frame the strike as below:

strike = int(far_OTM_CE_strike)
symbol_name = f"NIFTY 06 MAR {strike} CALL"

Hi @Ajay_Singh_Rajput ,

You may need to upgrade the codebase to latest version 3.0.6.

  • Open Command Prompt: Press Win, type cmd, and press Enter.
  • Install Dhan-Tradehull: Run pip install Dhan-Tradehull
  • Confirm the installation by running pip show Dhan-Tradehull

Guide to use the updated codebase:
Video reference : https://www.youtube.com/watch?v=P9iPYShakbA

Refer the below pypi link for more details:
https://pypi.org/project/Dhan-Tradehull/

Hi @anandc ,

There seems to be no issue , kindly check:

Thank You ! Saw the Video, its working now

Dear @Tradehull_Imran Sir,

Can you Provide Tested framework reference code for options trading like Straddle or Strangle Strategies

Thanks in advance

  1. Thanks for clarifying earlier doubt. So basically session 5 to 10 in season 1 series, we dont need to watch that, correct? one can directly start watching from advanced session 1.

  2. why is below giving an error (advanced session 1):

Blockquote
(Pdb++) import matplotlib.pyplot as plt
*** ModuleNotFoundError: No module named ‘matplotlib’
(Pdb++)

@Tradehull_Imran
Sir
Dhan have started providing 20-level market depth, but 99% of traders don’t know how to make WebSocket connections or send API requests to access the 20-level market depth.

Dhan started providing 20-level data, but if we cannot make use of it, then it is useless.

I’ve been trying but have faced many issues, and there is no one to help resolve them.
Please make make a video explaining it or provide the Python code. It would be very useful for thousands of traders.
If you truly want to help traders with your 20-level market depth data, please provide the code or make a useful video on it.
You can check out my code below.


import websocket
import json
import struct
def process_depth(raw_data):
    index, output, exchange_map = 0, {"data": {}, "status": "success"}, {1: 'NSE', 2: 'NSE_FNO', 3: 'BSE', 4: 'BSE_FNO'}
    header_fmt, depth_fmt, levels = '<HBBII', '<dII', 20
    header_size, level_size = struct.calcsize(header_fmt), struct.calcsize(depth_fmt)
    
    while index + header_size <= len(raw_data):
        msg_len, feed_code, exch_code, sec_id, _ = struct.unpack(header_fmt, raw_data[index:index + header_size])
        expected_length = header_size + (levels * level_size)
        if index + expected_length > len(raw_data): break
        
        side, exchange = {41: "buy", 51: "sell"}.get(feed_code), exchange_map.get(exch_code, f'UNKNOWN_{exch_code}')
        if not side: index += msg_len; continue
        
        output["data"].setdefault(exchange, {}).setdefault(str(sec_id), {"depth": {"buy": [], "sell": []}})
        depth_data = raw_data[index + header_size: index + expected_length]
        
        output["data"][exchange][str(sec_id)]["depth"][side] = [{
            "price": round(price, 2), "quantity": qty, "orders": orders
        } for price, qty, orders in struct.iter_unpack(depth_fmt, depth_data)]
        
        index += expected_length
    return output
def on_message(ws, msg): print("Received:", process_depth(msg))
def on_error(ws, err): print("Error:", err)
def on_close(ws, *_): print("WebSocket closed")
def on_open(ws):
    print("Connected")
    ws.send(json.dumps({
        "RequestCode": 23, "InstrumentCount": 5,
        "InstrumentList": [{"ExchangeSegment": "NSE_EQ", "SecurityId": str(id)} for id in [3787, 3045, 1333, 3456, 15355]] }))
def start_ws():
    ws = websocket.WebSocketApp(
        f"wss://depth-api-feed.dhan.co/twentydepth?token={access_token}&clientId={client_id}&authType=2",
        on_message=on_message, on_error=on_error, on_close=on_close )
    ws.on_open = on_open
    ws.run_forever()
if __name__ == "__main__": start_ws()

Error: [Errno 104] Connection reset by peer
WebSocket closed

please make a video on how to get 20 level market data.
Please also explain, how to send multiple json requests.
Bcz we can send upto 50 instruments in single json requests.
So, I want to send multiple json requests.Howwww???

SIR WEBSOKET GIVING WRONG DATA PS C:\Users\ACER\Documents\Algo\Dependencies> & C:/Users/ACER/Documents/Algo/Dependencies/.venv/Scripts/python.exe c:/Users/ACER/Documents/Algo/Dependencies/2.py
{‘type’: ‘Full Data’, ‘exchange_segment’: 1, ‘security_id’: 13, ‘LTP’: ‘5308.90’, ‘LTQ’: 16, ‘LTT’: ‘11:26:00’, ‘avg_price’: ‘5314.43’, ‘volume’: 202362, ‘total_sell_quantity’: 32075, ‘total_buy_quantity’: 32242, ‘OI’: 0, ‘oi_day_high’: 0, ‘oi_day_low’: 0, ‘open’: ‘5370.00’, ‘close’: ‘5370.00’, ‘high’: ‘5370.05’, ‘low’: ‘5280.00’, ‘depth’: [{‘bid_quantity’: 3, ‘ask_quantity’: 20, ‘bid_orders’: 1, ‘ask_orders’: 2, ‘bid_price’: ‘5308.05’, ‘ask_price’: ‘5308.90’}, {‘bid_quantity’: 35, ‘ask_quantity’: 19, ‘bid_orders’: 2, ‘ask_orders’: 4, ‘bid_price’: ‘5308.00’, ‘ask_price’: ‘5308.95’}, {‘bid_quantity’: 94, ‘ask_quantity’: 38, ‘bid_orders’: 1, ‘ask_orders’: 5, ‘bid_price’: ‘5307.90’, ‘ask_price’: ‘5309.30’}, {‘bid_quantity’: 29, ‘ask_quantity’: 1, ‘bid_orders’: 1, ‘ask_orders’: 1, ‘bid_price’: ‘5307.30’, ‘ask_price’: ‘5310.00’}, {‘bid_quantity’: 125, ‘ask_quantity’: 6, ‘bid_orders’: 1, ‘ask_orders’: 1, ‘bid_price’: ‘5306.95’, ‘ask_price’: ‘5310.10’}]}

Hi @Tradehull_Imran sir,

thank you, but that day, at that particular moment, got that error, after that till date working properly… today, got a new error-

  File "D:\Algo\Dhan_Tradehull_V2.py", line 1175, in get_order_status
    raise Exception('Check the order id, Error as None')
Exception: Check the order id, Error as None
During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "firstalgo_opt_4.py", line 243, in <module>
    if tsl.get_order_status(entry_order_id) == "TRADED":
  File "D:\Algo\Dhan_Tradehull_V2.py", line 1190, in get_order_status
    'data':response,
UnboundLocalError: local variable 'response' referenced before assignment

order was plced but while fetching its order _id, this error and after that sl_order was not placed…

if tsl.get_order_status(entry_order_id) == "TRADED":
                client_data["trade_open"] = True
                client_data["order_price"] = tsl.get_executed_price(entry_order_id)
                entry_time_exchg = tsl.get_exchange_time(etry_order_id)
                log_and_print(f"Order Execution time (Exchange) = {entry_time_exchg}", client_id)

                # Stop loss is 20% of order price
                sl_price = round(client_data["order_price"] * (0.80 if direction == "BUY" else 1.20), 2)
                try:
                    # Stop Loss Order placement SL-M order give guaranteed exit, but ther are chances of slippage with SL-M order 
                    # "Once the trigger price is hit, executes the order at market price, whatever that may be."
                    sl_order_id = tsl.order_placement(option_symbol, "NFO", client_qty, 0, sl_price, "SL-M", "SELL" if direction == "BUY" else "BUY", "MIS")
                    log_and_print(f"SL Order ID= {sl_order_id} placed", client_id, color=Fore.GREEN)
                    client_data["sl_order_id"]= sl_order_id
                except Exception as e:
                    log_and_print(f"Stop Loss (SL-M) Order placement failed: {e}", client_id)
                    sl_order_id = None

please check, m I placing the SL order in correct manner?

Hi @saurabha213 ,

  1. You can start watching from advanced session only if you have covered python basics, else can only ignore the websocket part and continue watching.
  2. It seems matplotlib is not been installed in your system, run the below code to install :
pip install matplotlib
1 Like

Dear @Tradehull_Imran sir
Thanks for ur help… it works

Hi @Raju2 ,

We will be releasing it by next week.

Hi @Rahul_kumar6 ,

Do make sure to use parameter as exchange = ‘INDEX’.

Hi @anandc ,

Make sure the order id you are passing is correct;

order_status = tsl.get_order_status(entry_order_id)
if order_status == 'TRADED':

The SL order will be placed only if the order status = ‘TRADED’

2 Likes

Hi @Tradehull_Imran sir,

How to get current day OHL data

@Tradehull_Imran could u please help me with session 5 video. I am not able to find it however looking into the folder I see we have covered may things ther or probable we have add different segments. I only get Saturday & Sunday to understand on this. I you could plase help.

Thanks
Sanjeev Ranjan

Akhri din for people who can’t really master their strategies or their emotions.

The level of growth and profits manual trading gives is exponential. The skill is so tough to achieve that people instead go for other variations of trading.

Trading is a combination of art and science and without the art part, no matter who says what, you can’t really achieve WEALTH. You can be RICH through algos, but NOT WEALTHY.

Talking from an extensive experience.

1 Like

Many thanks Sir for clarifying.

1 Like

Hi sir, Regarding today 8 March 2025 uploaded video. In the video you have made a typo in line number 33 of lower breakout in the pre market scan. you typed as close > middle Bollinger band.
correct code us : close< lower bolinger band

1 Like