Learn Algo Trading with Python | Codes | Youtube Series

hi @Rajashekhar_Rangappa,

Today, again Finifty call was bought iinstead of NIFTY… !!! Very strange… isn’t it?

@Tradehull_Imran Sir… pls look into this issue…

clearly, can be seen that EMA and other values are for NIFTY and instead FINIFTY got bought… !!!

from Episode 7, part 2

there is a problem in no of order placed code

no_of_orders_placed = orderbook_df[orderbook_df['qty'] > 0].shape[0] + completed_orders_df[completed_orders_df['qty'] > 0].shape[0]

orderbook_df[orderbook_df[‘qty’] > 0].shape[0] will give you a numeric value but the
completed_orders_df[completed_orders_df[‘qty’] > 0].shape[0] will give you an error as dictionary “completed_orders_df” is created from “completed_orders” which is a list, which is empty at start of the program.

please correct me if i m wrong…

1 Like

20 MARKET DEPTH ( 20 Market Depth - DhanHQ Ver 2.0 / API Document) NOT RETURNING ANYTHING. KINDLY HELP @RahulDeshpande

import struct
import logging
import websocket
import json
import threading
import time
from datetime import datetime

logging.basicConfig(level=logging.DEBUG)

CLIENT_CODE = ""
TOKEN_ID = ""

# Test with fewer instruments for debugging
sub_msg = {
    "RequestCode": 23,
    "InstrumentCount": 2,
    "InstrumentList": [
        {"ExchangeSegment": "NSE_FNO", "SecurityId": "35009"},
        {"ExchangeSegment": "NSE_FNO", "SecurityId": "35010"}
    ]
}

live_20_depth_data = {inst['SecurityId']: {'bid': [], 'ask': [], 'last_update': None} for inst in sub_msg['InstrumentList']}
print(f"Initialized live_20_depth_data with keys: {list(live_20_depth_data.keys())}")

def parse_20_depth_packet(binary_message):
    """Parse binary packet."""
    try:
        logging.debug("Raw binary message: %s", binary_message.hex())
        header_format = '<hBBII'
        depth_record_format = '<dII'
        header_size = struct.calcsize(header_format)
        depth_record_size = struct.calcsize(depth_record_format)

        msg_length, response_code, exchange_segment, security_id, seq_num = struct.unpack(header_format, binary_message[:header_size])
        logging.debug(f"Header parsed: Length={msg_length}, Code={response_code}, Segment={exchange_segment}, SecurityId={security_id}, SeqNum={seq_num}")

        offset = header_size
        bid_depth, ask_depth = [], []

        if response_code == 41:
            for i in range(20):
                price, qty, orders = struct.unpack(depth_record_format, binary_message[offset:offset + depth_record_size])
                bid_depth.append((price, qty, orders))
                offset += depth_record_size
            return bid_depth, None, security_id

        elif response_code == 51:
            for i in range(20):
                price, qty, orders = struct.unpack(depth_record_format, binary_message[offset:offset + depth_record_size])
                ask_depth.append((price, qty, orders))
                offset += depth_record_size
            return None, ask_depth, security_id

        return None, None, None

    except Exception as e:
        logging.exception("Error parsing packet")
        return None, None, None

def on_message(ws, message):
    """Handle incoming WebSocket messages."""
    if isinstance(message, bytes):
        logging.debug(f"Binary message received: {message.hex()}")
        parse_20_depth_packet(message)
    else:
        logging.debug(f"Non-binary message received: {message}")

def on_open(ws):
    """Handle WebSocket connection open."""
    logging.info("Websocket connected")
    sub_message = json.dumps(sub_msg)
    ws.send(sub_message)
    logging.info(f"Subscription sent: {sub_message}")

def start_websocket():
    """Start WebSocket feed."""
    ws_url = f"wss://depth-api-feed.dhan.co/twentydepth?token={TOKEN_ID}&clientId={CLIENT_CODE}&authType=2"
    
    ws = websocket.WebSocketApp(
        ws_url,
        on_open=on_open,
        on_message=on_message,
        on_error=lambda ws_, msg_: logging.error(f"WebSocket error: {msg_}"),
        on_close=lambda ws_, code_, msg_: logging.info(f"WebSocket closed")
    )
    
    ws.run_forever(ping_interval=30)

if __name__ == "__main__":
    threading.Thread(target=start_websocket).start()

PS D:\ALGO> PY '.\20 MARKET DEPTH DATA.py'
Initialized live_20_depth_data with keys: ['35009', '35010']
INFO:websocket:Websocket connected
INFO:root:Websocket connected
INFO:root:Subscription sent: {"RequestCode": 23, "InstrumentCount": 2, "InstrumentList": [{"ExchangeSegment": "NSE_FNO", "SecurityId": "35009"}, {"ExchangeSegment": "NSE_FNO", "SecurityId": "35010"}]}
DEBUG:websocket:Sending ping
DEBUG:websocket:Sending ping
DEBUG:websocket:Sending ping
DEBUG:websocket:Sending ping

Hi @Tradehull_Imran ,
Any update on this one…?

Today as well I’m seeing alerts for FINNIFTY…

2 Likes

This last line of code is incomplete. Please don’t use this last line of code. It’s only an information on Slicing the order, if you exceed the quantity restricted in specific to each stock / Indices, as very much explained by Imran Ali Sir, in Part 2 0f Episode 7.

Hi,
I too faced the same issue… also occurred few weeks ago. wrote here but nothing happened… I think its an issue with the Wrapper file… Dhan_TradeHull file, as we are sending signals to this and then from here they are sent to api.dhan.com or something like that… we are sending NIFTY and some kind of mismatch is going inside the wrapper file which send FINNIFTY to API to fetch the data… Now its upto Dhan to accept this mistake and correct it… BUt suck kind of mistake never happened with SENSEX… it never mistook it as BANKEX…AS i hv traded it many times

Hi Imran ji. Any update on bracket order placement using dhan tradehull pls ?

Installed Python 3.8.0 on Windows machine

Stuck in the Session2 – Installation, unable to proceed, receiving below error.
Please advise.

Your Python version is not 3.8.0. Please uninstall all other versions.
If you are using Conda, please uninstall it, as it interferes with library installation.

Yes @Tradehull_Imran Ji,
We are waiting since long for Bracket Order training for Option trades.
@RahulDeshpande @Dhan @Hardik

1 Like

@Tradehull_Imran , @dhan,@RahulDeshpande,@Hardik,

both Bracket and Super (beta) orders training vdoz for options…

1 Like


Manish1

1d

@Hardik @Tradehull_Imran how can i get historical data for 1 month for 1 hour candle ohlc , currently i am getting for 5 days only data = tsl.get_historical_data(tradingsymbol=“13”, exchange=“INDEX”, timeframe=“60”)

Hi @Tradehull_Imran,

there is some problem, scanning Nifty index but executing orders for Finnifty options, please check with API.

1 Like

mate, Its been a month since people started reporting the issue. Still no resolution. :rage: @Dhan @RahulDeshpande

1 Like


My algo crashed due to this. I’m really pissed.

If they can open-source the SDK, we can fix and release it.

Aaj phir FINIFTY Call instead of NIFTY… Can you confirm, pls, what came at ur end…

HI,

I spoke with someone from Dhan regarding the recurring issue of missing NIFTY and FINNIFTY options. They mentioned that the problem is not on their end and stated, “We have assigned this task to Imran, and he is responsible for handling it.”. see this kind of reply… :face_with_raised_eyebrow: :face_with_raised_eyebrow:

Checking this - will get back to you.

2 Likes

@Tradehull_Imran , In the latest episode you have explained option selling in the code, but how do we trail the profit in option selling?

Hi @Tradehull_Imran , @RahulDeshpande ,

sending the console output of same algo… see the topmost, red colored info and then see the GREEN colored info at bottom.

ab aise mesg bhi dalna pad rahan hain…

Initially it gave FINNIFTY instead of NIFTY, then after re-running, it gave NIFTY for NIFTY… And I have hardocded NIFTY in algo code, I mostly trade NIFTY and SENSEX… never ever traded or tried FINNIFTY…

3 Likes

@RahulDeshpande @Tradehull_Imran I need hostorical data for one month for one hour candle can u help me with this ???