API : Share the challenges youre facing currently

What are the major challenges you are facing currently wrt to API trading where you require help? Whether it’s about learning the ropes or overcoming specific hurdles, your insights would be invaluable.

Do let us know and we would like to help you in the best way we can.

Tagging a few folks for your point of view.

@Sammy @t7support @neo2564 @asijavk @Pranav_Deshmukh @algotric @Dev @Vetrivel_Dhandapani @abhimaneu @Vikash_Saini @Ravindra_Bagate @TraderX @senthil_kumar @Boss @Abhishek_Rodwal @amarjambukar @

Thank you.
I have subscribed for marketfeed.
I have written the code, but somehow it’s not working. some errors are coming.

Is there anyone who could rewrite code again? I’m ready to pay for it.

Thanks again.
Ravindra

1 Like

Hi Team,

I had mentioned an issue sometime back with modify command.
mentioning once again here…

dhan.modify_order does not respond.
Can you check at your end if you think my code is ok.

from dhanhq import marketfeed
from dhanhq import dhanhq
from json import loads
import pandas as pd
import pandas.core.series as Series
import time

client_id = “”
access_token = “”
dhan = dhanhq(client_id,access_token)

#Place a buy order in NFO
def place_Buy(security_id_1, price1,trigger_price1,quantity1):
Buy_option_id = dhan.place_order(
transaction_type=dhan.BUY,
exchange_segment=dhan.BSE_FNO,
product_type=dhan.INTRA,
order_type=dhan.SL,
security_id=security_id_1,
quantity=quantity1,
disclosed_quantity=0,
price=price1,
trigger_price=trigger_price1,
after_market_order=False,
bo_profit_value=0,
bo_stop_loss_Value=0,
drv_expiry_date=None,
drv_options_type=None,
drv_strike_price=None
)
return Buy_option_id

security_id_1 = ‘870827’
quantity1 = 10
price1 = 45
trigger_price1 = price1 - 0.1
buy_order_1 = place_Buy(security_id_1,price1,trigger_price1,quantity1)
order_Id_1 = buy_order_1[‘data’][‘orderId’]
print(“Order status:”, order_Id_1)

time.sleep(3)

new_price = price1 + 2
new_triggerprice = price1 + 1.9

dhan.modify_order(
order_id=order_Id_1,
order_type=dhan.SL,
leg_name=‘’,
quantity=quantity1,
price= new_price,
disclosed_quantity=10,
trigger_price= new_triggerprice,
validity=dhan.DAY
)
print (“has been modified”)

1 Like

@Ravindra_Bagate

if I understand your question correctly, you want to use the LTP after fetching it from marketfeed. In that caseyou can use the following code.

Dear @RahulDeshpande ,

The problem I am facing is I want to exit all open position with API without defining any quantity, which as of now is not possible with JSON generated .

I am using NEXTLEVELBOT and the syntax used is
[{“OTYPE”:“PE”,“AS”:“BANKNIFTY”,“E”:“NFO”,“P”:“INTRADAY”,“AT”:“DHANHQ”}]

this closes all open positions.

  1. When with the above syntax, it is possible to close all positions, the JSON which must be generated at NEXTLEVELBOT is not defining any quantity, then this should also be possible to close all open position directly with DHAN.

  2. If as of now if cannot be Integrated directly for JSON generation, then in that case you can provide JSON to me for closing all open positions, so that I can use it in my algorithm directly from trading view to DHAN, avoiding third party application, this will also solve latency issues .

  3. This will help across all , who are using my algorithms for trading on DHAN.

Warm Regards

V K Asija

Thank you @Dev
I tried this. but not worked. I think there maybe error at some other place.
my code are as below:-----

import pandas as pd
import logging
import asyncio
import time
from datetime import datetime, timedelta
from dhanhq import dhanhq, marketfeed
from dhanhq.dhanhq import dhanhq
from dhanhq.marketfeed import DhanFeed
from pathlib import Path
from webbrowser import open as web_open

Constants

client_id = 1208340001-------
access_token = “eyJ0eXAiOiJKV1QiLCJ”
subscription_code = marketfeed.Ticker
HIGH_RANGE = 22040
LOW_RANGE = 22025
PROFIT_BOOKING_THRESHOLD = 100
START_TIME = “09:20:00”
END_TIME = “15:30:00”

Configure logging

logging.basicConfig(level=logging.DEBUG)

Functions

def atm_strike(spot_price):
“”"
Calculate the At-The-Money (ATM) strike price based on the spot price.

Args:
    spot_price (float): The current spot price.

Returns:
    int: The ATM strike price.
"""
if spot_price % 100 < 25:
    return int(spot_price / 100) * 100
elif spot_price % 100 >= 25 or spot_price % 100 < 75:
    return int(spot_price / 100) * 100 + 50
else:
    return int(spot_price / 100) * 100 + 100

def get_symbol_name(symbol, expiry, strike, strike_type):
“”"
Generate the symbol name for an instrument.
Args:
symbol (str): The symbol name.
expiry (str): The expiry date.
strike (int): The strike price.
strike_type (str): The type of option (CE or PE).

Returns:
    str: The generated symbol name.
"""
return f"{symbol}-{expiry}-{strike}-{strike_type}"

def get_instrument_token():
“”"
Retrieve instrument tokens from a CSV file.
Returns:
dict: A dictionary mapping symbols to instrument tokens.
“”"
df = pd.read_csv(‘api-scrip-master.csv’)
token_dict = {}
for _, row in df.iterrows():
trading_symbol = row[‘SEM_TRADING_SYMBOL’]
exm_exch_id = row[‘SEM_EXM_EXCH_ID’]
if trading_symbol not in token_dict:
token_dict[trading_symbol] = {}
token_dict[trading_symbol][exm_exch_id] = row.to_dict()
return token_dict

def main():
# Initialize DhanHQ client
dhan = dhanhq(client_id=client_id, access_token=access_token)

# Get instrument tokens
token_dict = get_instrument_token()

# Define instruments
symbol = 'NIFTY'
expiry = 'May2024'

# Initialize position flags
ce_position = False
pe_position = False

# Initialize profit booking variables
last_ce_ltp = None
last_pe_ltp = None
ce_profit_booked = False
pe_profit_booked = False

while True:
    # Get current time
    current_time = datetime.now().strftime("%H:%M:%S")
    # Check if within trading hours
    if START_TIME <= current_time <= END_TIME:
        # Get Nifty LTP
        nifty_ltp = dhan.intraday_minute_data(
        security_id=token_dict,
        exchange_segment='NSE_FNO',
        instrument_type='OPTIDX'
        )

        logging.info(f"Nifty LTP: {nifty_ltp}")

        # Check if profit booking condition is met for CE
        if ce_position and last_ce_ltp is not None and nifty_ltp - last_ce_ltp >= PROFIT_BOOKING_THRESHOLD and not ce_profit_booked:
            logging.info("Profit booking for CE triggered")
            # Perform profit booking logic for CE here
            ce_profit_booked = True

        # Check if profit booking condition is met for PE
        if pe_position and last_pe_ltp is not None and last_pe_ltp - nifty_ltp >= PROFIT_BOOKING_THRESHOLD and not pe_profit_booked:
            logging.info("Profit booking for PE triggered")
            # Perform profit booking logic for PE here
            pe_profit_booked = True

        # Update last CE LTP for next iteration
        last_ce_ltp = nifty_ltp if ce_position else last_ce_ltp

        # Update last PE LTP for next iteration
        last_pe_ltp = nifty_ltp if pe_position else last_pe_ltp

        # Check if LTP crosses above high range
        if nifty_ltp > HIGH_RANGE:
            if not ce_position:
                # Enter CE
                atm_strike_price = atm_strike(nifty_ltp)
                ce_id = token_dict[get_symbol_name(symbol, expiry, atm_strike_price, 'CE')]['NSE']['SEM_SMST_SECURITY_ID']
                dhan.place_order(security_id=ce_id, exchange_segment=dhan.NSE, transaction_type=dhan.BUY, quantity=50, order_type=dhan.MARKET, product_type=dhan.INTRA, price=0)
                ce_position = True

            # Exit PE if entered
            if pe_position:
                pe_id = token_dict[get_symbol_name(symbol, expiry, atm_strike_price, 'PE')]['NSE']['SEM_SMST_SECURITY_ID']
                dhan.place_order(security_id=pe_id, exchange_segment=dhan.NSE, transaction_type=dhan.SELL, quantity=50, order_type=dhan.MARKET, product_type=dhan.INTRA, price=0)
                pe_position = False

        # Check if LTP crosses below low range
        elif nifty_ltp < LOW_RANGE:
            if not pe_position:
                # Enter PE
                atm_strike_price = atm_strike(nifty_ltp)
                pe_id = token_dict[get_symbol_name(symbol, expiry, atm_strike_price, 'PE')]['NSE']['SEM_SMST_SECURITY_ID']
                dhan.place_order(security_id=pe_id, exchange_segment=dhan.NSE, transaction_type=dhan.BUY, quantity=50, order_type=dhan.MARKET, product_type=dhan.INTRA, price=0)
                pe_position = True

            # Exit CE if entered
            if ce_position:
                ce_id = token_dict[get_symbol_name(symbol, expiry, atm_strike_price, 'CE')]['NSE']['SEM_SMST_SECURITY_ID']
                dhan.place_order(security_id=ce_id, exchange_segment=dhan.NSE, transaction_type=dhan.SELL, quantity=50, order_type=dhan.MARKET, product_type=dhan.INTRA, price=0)
                ce_position = False

    # Sleep for a while before checking again
    time.sleep(1)

if name == “main”:
main()

Hi, I have issue with script to convert intraday to CNC and vice versa.
To many options need to provide to convert.
In my opinion qty and order no is sufficient.

Dhan Team, might be able to help you.
You can also try Chatgpt/Gemini. It’s helpful in code correction.

How about making the API charges zero like some other brokers :slightly_smiling_face: ? Can do without the price hurdle especially for small time traders. For active API traders anyway they generate enough brokerage and so API infra cost can be offset against that.

1 Like
  1. Like all other brokers, allow API call to fetch LTP.
  2. Take feedback such as this seriously.
1 Like

Major challenge these days is that trouble in connecting market data via websocket. Recently I have struggled a lot for websocket connection.

Also, installing library and its dependent libraries.