Learn Algo Trading with Python | Codes | Youtube Series

Hi @Himansshu_Joshi

use below example code for order modification


modified_order = tsl.modify_order(order_id=sl_orderid,order_type="STOPLIMIT",quantity=25,price=price,trigger_price=trigger_price)

Also, do use this codebase file : Dhan_Tradehull_V2.py - Google Drive

hi @avinashkumar07412

were you running multiple algo files simultaneously.
Also soon, we will be releasing a new solution for rate limit issues.

Hi @Vasili_Prasad

The code seems to be working correctly on my end

code used

import pdb
import time
import datetime
import traceback
from Dhan_Tradehull_V2 import Tradehull
import pandas as pd
from pprint import pprint
import talib
from datetime import datetime


client_code = ""
token_id    = ""

tsl         = Tradehull(client_code,token_id)


# Define the list of options
call_list = ['NIFTY 19 DEC 24100 CALL', 'NIFTY 19 DEC 24100 PUT']

while True:
    try:
        # Get current time
        current_time = datetime.now()
        print(f"Current Time: {current_time}")

        # Fetch LTP data
        ltp_data = tsl.get_ltp_data(names=call_list)

        # Extract LTP values
        ce_ltp = ltp_data.get('NIFTY 19 DEC 24100 CALL', 0)
        pe_ltp = ltp_data.get('NIFTY 19 DEC 24100 PUT', 0)

        # Calculate ATM combined premium
        atm_combined_premium = round(ce_ltp + pe_ltp, 1)
        print(f"ATM Combined Premium: {atm_combined_premium}")

    except Exception as e:
        print("An error occurred:")
        print(e)

    # Pause for a short interval
    time.sleep(0.5)

do retry the same

Hi @Vasili_Prasad

The options_data seems to be None, it does not have any data

  1. Do send the complete error … example complet error below

X.1 Copy me for Codebase support>py "Dhan Login ltp and hist.py"
Codebase Version 2.3 : Solved - ATM issues
-----Logged into Dhan-----
reading existing file all_instrument 2024-12-18.csv
Got the instrument file
[0] > c:\users\imran\desktop\dhan lecture sessions\forum support\forum code questions\x.1 copy me for codebase support\dhan login ltp and hist.py(20)<module>()
-> margin = tsl.margin_calculator(tradingsymbol='ACC', exchange='NSE', transaction_type='BUY', quantity=2, trade_type='MIS'

2, See if the Dhan data is still active, and not expired

  1. Also, do use this codebase file : Dhan_Tradehull_V2.py - Google Drive

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

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

Tagging

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

Tagging

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

1 Like

Hi @sammed_patil

“12-12-2024” is a expired contract.

Also, We have upgraded the code for ATM_Strike_Selection

ce_strike, pe_strike, strike = tsl.ATM_Strike_Selection(Underlying='NIFTY', Expiry=0)


Explanation for Expiry (int): The expiry to select.
0 - Current week/month (depending on expiry type)
1 - Next week/month (depending on expiry type)
and so on for subsequent weeks/months.

Also, do use this codebase file : Dhan_Tradehull_V2.py - Google Drive

Hi @Rajashekhar_Rangappa

See reference code,


				options_name                      = orderbook[name]['options_name']
				options_chart                     = tsl.get_historical_data(tradingsymbol = options_name,exchange = 'NFO',timeframe="5")
				options_chart['atr'] 			  = talib.ATR(options_chart['high'], options_chart['low'], options_chart['close'], timeperiod=14)
				rc_options                        = options_chart.iloc[-1]
				sl_points                         = rc_options['atr']*atr_multipler
				options_ltp                       = tsl.get_ltp_data(names = options_name)[options_name]
				tsl_level                         = options_ltp - sl_points

				if tsl_level > orderbook[name]['tsl']:
					trigger_price = round(tsl_level, 1)
					price         = trigger_price - 0.05
					tsl.modify_order(order_id=orderbook[name]['sl_orderid'],order_type="STOPLIMIT",quantity=25,price=price,trigger_price=trigger_price)
					orderbook[name]['tsl'] = tsl_level

Also, do use this codebase file : Dhan_Tradehull_V2.py - Google Drive

1 Like

Hi @SUDIP_NATH

‘errorMessage’: ‘Order Is Cancelled.kindly Refresh Your Orderbook’
I think mostly the order has been cancelled and the code is retrying to cancel it, thus the error

Hi @avinashkumar07412
I will check on this one.

Hi @Rajashekhar_Rangappa

we used Dhan_websocket.py to fetch LTP, but using websocket method was complex.
so we have now switched to rest api calls to get the ltp,
this gives us a very easy wasy to get ltp
`
example :
ltp = tsl.get_ltp_data(names = [‘NIFTY 19 DEC 24000 CALL’, ‘NIFTY 19 DEC 24000 PUT’])

`

yes we can run the algo without using websocket file at all. soon we will deprecate the websocket method.

1 Like

This is a Test question

Hi @Tradehull_Imran
I am facing issue while running codebase usage file

import pdb
import time
import datetime
import traceback
from Dhan_Tradehull import Tradehull
import pandas as pd
from pprint import pprint
import talib


client_code = ""
token_id    = ""
tsl         = Tradehull(client_code,token_id)


all_ltp_data   = tsl.get_ltp_data(names = ['NIFTY 19 DEC 24000 akshdgasjhgdhgasjgdhjagsdCALL', 'NIFTY 19 DEC 24000 PUT', "ACC", "CIPLA"])
acc_ltp = all_ltp_data['ACC']
pe_ltp  = all_ltp_data['NIFTY 19 DEC 24000 PUT']



stock_name = 'NIFTY'
ltp   = tsl.get_ltp_data(names = [stock_name])[stock_name]




chart = tsl.get_historical_data(tradingsymbol = 'NIFTY',  exchange = 'INDEX',timeframe="DAY")
data  = tsl.get_historical_data(tradingsymbol = 'NIFTY 19 DEC 24000 CALL'     ,exchange = 'NFO'  ,timeframe="15")



order_status  = tsl.get_order_status(orderid=82241218256027)
order_price   = tsl.get_executed_price(orderid=82241218256027)
order_time    = tsl.get_exchange_time(orderid=82241218256027)


positions = tsl.get_positions()
orderbook = tsl.get_orderbook()
tradebook = tsl.get_trade_book()
holdings = tsl.get_holdings()


ce_name, pe_name, strike = tsl.ATM_Strike_Selection(Underlying='NIFTY', Expiry=0)


ce_name, pe_name, ce_strike, pe_strike = tsl.OTM_Strike_Selection(Underlying='NIFTY', Expiry=0, OTM_count=3)

ce_name, pe_name, ce_strike, pe_strike = tsl.ITM_Strike_Selection(Underlying='NIFTY', Expiry=0, OTM_count=5)

# Equity
entry_orderid  = tsl.order_placement(tradingsymbol='ACC' ,exchange='NSE', quantity=1, price=0, trigger_price=0,    order_type='MARKET',     transaction_type='BUY',   trade_type='MIS')
sl_orderid     = tsl.order_placement(tradingsymbol='ACC' ,exchange='NSE', quantity=1, price=0, trigger_price=2200, order_type='STOPMARKET', transaction_type ='SELL', trade_type='MIS')

# Options
entry_orderid  = tsl.order_placement(tradingsymbol='NIFTY 19 DEC 24400 CALL' ,exchange='NFO', quantity=50, price=0, trigger_price=0, order_type='MARKET', transaction_type='BUY', trade_type='MIS')
sl_orderid     = tsl.order_placement(tradingsymbol='NIFTY 19 DEC 24400 CALL' ,exchange='NFO', quantity=25, price=29, trigger_price=30, order_type='STOPLIMIT', transaction_type='SELL', trade_type='MIS')

modified_order = tsl.modify_order(order_id=sl_orderid,order_type="STOPLIMIT",quantity=50,price=price,trigger_price=trigger_price)

order_ids      = tsl.place_slice_order(tradingsymbol="NIFTY 19 DEC 24400 CALL",   exchange="NFO",quantity=5000, transaction_type="BUY",order_type="LIMIT",trade_type="MIS",price=0.05)



margin = tsl.margin_calculator(tradingsymbol='ACC', exchange='NSE', transaction_type='BUY', quantity=2, trade_type='MIS', price=2180, trigger_price=0)

margin = tsl.margin_calculator(tradingsymbol='NIFTY 19 DEC 24400 CALL', exchange='NFO', transaction_type='SELL', quantity=25, trade_type='MARGIN', price=43, trigger_price=0)

margin = tsl.margin_calculator(tradingsymbol='NIFTY 19 DEC 24400 CALL', exchange='NFO', transaction_type='BUY', quantity=25, trade_type='MARGIN', price=43, trigger_price=0)
margin = tsl.margin_calculator(tradingsymbol='NIFTY DEC FUT', exchange='NFO', transaction_type='BUY', quantity=25, trade_type='MARGIN', price=24350, trigger_price=0)


exit_all       = tsl.cancel_all_orders()



error


C:\Users\imran\Desktop\Dhan Lecture Sessions\Session with Dhan Team\3.1 Codebase Upgrade>py "How to use updated codebase.py"
Codebase Version 3
-----Logged into Dhan-----
reading existing file all_instrument 2024-12-18.csv
Got the instrument file
Exception for instrument name NIFTY 19 DEC 24000 AKSHDGASJHGDHGASJGDHJAGSDCALL as Check the Tradingsymbol
Traceback (most recent call last):
  File "How to use updated codebase.py", line 28, in <module>
    chart = tsl.get_historical_data(tradingsymbol = 'NIFTY',  exchange = 'INDEX',timeframe="DAY")
  File "C:\Users\imran\AppData\Local\Programs\Python\Python38\lib\site-packages\Dhan_Tradehull\Dhan_Tradehull.py", line 441, in get_historical_data
    time.sleep(2)
KeyboardInterrupt
^C
C:\Users\imran\Desktop\Dhan Lecture Sessions\Session with Dhan Team\3.1 Codebase Upgrade>









Hello Sir @Tradehull_Imran

You taught us how to retrieve ATM, OTM, and ITM strikes along with their LTP. We also learned how to apply indicators and take trades based on them. However, I want to dynamically select an ITM strike and take trades based on the indicator value of that specific strike, rather than relying on the indicator value of the index or futures.

For example, if the Bank Nifty spot price is 52,000, I want to sell an ITM +10 strike, such as the 51,000 Call or 53,000 Put, based on a SuperTrend sell signal for that particular ITM strike—not the index or future.

Hi @Tradehull_Imran , thanks for the info. i got the ltp using the TradehullV2 file however, there was a problem with numpy but i upgraded pandas and it went ok. Thanks again

1 Like

Hi,

It’s due to wrong symbol being called as stated in the exception message.

1 Like

Hi @Tradehull_Imran,

Thanks, already made the code for fetching Intraday margin.

import requests
import pandas as pd
import time
import os

client_code = ""
token_id = ""

# Function to fetch the instrument file and map symbols to security IDs
def get_instrument_file():
    current_date = time.strftime("%Y-%m-%d")
    expected_file = 'all_instrument ' + str(current_date) + '.csv'
    
    for item in os.listdir("Dependencies"):
        path = os.path.join("Dependencies", item)
        if item.startswith('all_instrument') and current_date not in item.split(" ")[1]:
            if os.path.isfile(path):
                os.remove(path)
    
    if expected_file in os.listdir("Dependencies"):
        try:
            print(f"Reading existing file {expected_file}")
            instrument_df = pd.read_csv(os.path.join("Dependencies", expected_file), low_memory=False)
        except Exception as e:
            print("Instrument file is not generated completely, fetching new file from Dhan")
            instrument_df = pd.read_csv("https://images.dhan.co/api-data/api-scrip-master.csv", low_memory=False)
            instrument_df.to_csv(os.path.join("Dependencies", expected_file), index=False)
    else:
        # Fetch the instrument file from Dhan
        print("Fetching new file from Dhan")
        instrument_df = pd.read_csv("https://images.dhan.co/api-data/api-scrip-master.csv", low_memory=False)
        instrument_df.to_csv(os.path.join("Dependencies", expected_file), index=False)
    
    return instrument_df

instrument_df = get_instrument_file()

symbol = input("Enter the stock symbol: ")
#price = input("Enter price: ")
#qty = input("Enter the quantity: ")


# Lookup the security ID based on the stock symbol
try:
    nse_row = instrument_df[(instrument_df['SEM_TRADING_SYMBOL'] == symbol) & (instrument_df['SEM_EXM_EXCH_ID'] == 'NSE')]
    
    if not nse_row.empty:
        security_id = nse_row['SEM_SMST_SECURITY_ID'].values[0]
        print(f"Security ID for {symbol} is {security_id}")
    else:
        print(f"Symbol {symbol} not found in NSE segment.")
        exit()
except Exception as e:
    print(f"Error occurred during lookup: {e}")
    exit()

url = "https://api.dhan.co/v2/margincalculator"

payload = {
    "dhanClientId": client_code,
    "exchangeSegment": "NSE_EQ",
    "transactionType": "BUY",
    "quantity": 1,
    "productType": "INTRADAY",
    "securityId": str(security_id),
    "price": 1,
    "triggerPrice": "0"
}

headers = {
    "access-token": token_id,
    "Content-Type": "application/json",
    "Accept": "application/json"
}

response = requests.post(url, json=payload, headers=headers)
margin_data = response.json()

# Extract the leverage value
leverage = margin_data.get('leverage', 'N/A')
print(f"Leverage: {leverage}")

1 Like

@Tradehull_Imran One more on your list, :smile: Getting error for

chart = tsl.get_historical_data(“SENSEX DEC FUT”, “BFO”, “5”)

Exception has occurred: TypeError
'NoneType' object is not subscriptable
  File "/Users/raj/Desktop/workstation/personal/trading-view/algo/dhan/bot.py", line 41, in apply_indicators
    chart['rsi'] = talib.RSI(chart['close'], timeperiod=14)
  File "/Users/raj/Desktop/workstation/personal/trading-view/algo/dhan/bot.py", line 120, in <module>
    chart = apply_indicators(chart)
TypeError: 'NoneType' object is not subscriptable

However, it works for
chart = tsl.get_historical_data(“NIFTY DEC FUT”, “NFO”, “5”) :confused:

sir @Tradehull_Imran , now how to fetch order ids for sliced orders. as i can handle 1 id fetch for my codes.

order_status = tsl.get_order_status(orderid=buy_entry_orderid)
                log_queue.put(f"Order Status: {order_status}")
                logging.info(f"Order Status: {order_status}")
                time.sleep(1)

                if order_status == "PENDING":
                    # Monitor stop-loss offset
                    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:
                        log_queue.put(f"Market price {current_market_price} is below stop-loss offset {stop_loss_offset}. Canceling order.")
                        tsl.Dhan.cancel_order(buy_entry_orderid)
                        log_queue.put(f"Order {buy_entry_orderid} canceled. Stopping algorithm.")
                        logging.info(f"Order {buy_entry_orderid} canceled. Stopping algorithm.")
                        break

                elif order_status == "TRADED":
                    buy_price = tsl.get_order_detail(orderid=buy_entry_orderid)['price']
                    target_price = buy_price + target_offset
                    stop_loss_price = stop_loss_offset
                    sl_limit_price = stop_loss_price - 1

                    # Place initial stop-loss order
                    stoploss_orderid = tsl.order_placement(trading_symbol, "NFO", qty, sl_limit_price, stop_loss_price, 'STOPLIMIT', 'SELL', 'MIS'
                    )
                    log_queue.put(f"Initial Stop Loss Order Placed. Order ID: {stoploss_orderid}")
                    logging.info(f"Initial Stop Loss Order Placed. Order ID: {stoploss_orderid}")
                    time.sleep(0.2)