Learn Algo Trading with Python | Codes | Youtube Series

Hi @Himansshu_Joshi

See below details for order modification
Get Order Modification

  • tsl.modify_order(order_id, order_type, quantity, price=0, trigger_price=0, disclosed_quantity=0, validity='DAY', leg_name=None)
  • Arguments:
    • order_id (str): The unique ID of the order to be modified.
    • order_type (str): Type of the order. Options include: - ‘LIMIT’: Limit order. - ‘MARKET’: Market order. - ‘STOPLIMIT’: Stop-loss limit order. - ‘STOPMARKET’: Stop-loss market order.
    • quantity (int): The updated quantity for the order.
    • price (float, optional): The updated price for the order (default is 0).
    • trigger_price (float, optional): The updated trigger price for the order (default is 0).
    • disclosed_quantity (int, optional): The quantity to disclose (default is 0).
    • validity (str, optional): Validity of the order. Options are: - ‘DAY’: Order remains valid for the trading day (default). - ‘IOC’: Immediate or cancel.
    • leg_name (str, optional): The specific leg to modify (used for bracket/CO orders). Options are: - ‘ENTRY_LEG’: Entry leg of the order. - ‘TARGET_LEG’: Target leg of the order. - ‘STOP_LOSS_LEG’: Stop-loss leg of the order. - If not applicable, leave as None.
  • Returns:
    • str: The modified order ID if the modification is successful.
    • Raises an exception if the modification fails.

example code

orderid = '12241210603927'
modified_order_id = tsl.modify_order(order_id=orderid,order_type="LIMIT",quantity=50,price=0.1,trigger_price=0)

Hi @vinay_kumaar

It seems that the in the 17 entry conditions, one of the condition is comparing the dataframe column to int

see below example

chart = tsl.get_historical_data(tradingsymbol = 'NIFTY',exchange = 'INDEX',timeframe="1")
chart['rsi'] = talib.RSI(chart['close'], timeperiod=14)

cc = chart.iloc[-1]

sc1 = chart['rsi'] > 60    # this is wrong condition we cant compare column to int
sc2 = cc['rsi'] > 60       # this is right condition we can compare value of completed candle rsi which is a float to a int

because of sc1 we will get the error of 
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Let me know if it solves the issue,
if not solved do share the code file to tradehull_mentorship@tradehull.com

Hi @Rajashekhar_Rangappa
I have tried the ADX code, it seems to be working fine.

The case may be that if we are not getting chart data itself, so the adx nan value may arise.
Please ensure that the chart dataframe/value are correct and is not nan

Hi @Scooby_Doo
Use below code to export chart data to excel


chart.to_csv('NIFTY.csv')

Hi @Rajat_Gupta

For mac do check this post

Hi @SUKANTA_MONDAL1

can you send me the high level code for the same, that you are currently working on.

Hi @thakurmhn

Do share the code file to tradehull_mentorship@tradehull.com

Hello @Tradehull_Imran Sir
SyntaxError: unexpected EOF while parsing ye massege aa rha hai.


aap ne jo suggestion diya tha (sc2 = cc[‘rsi’] > 60 # this is right condition we can compare value of completed candle rsi which is a float to a int)
code ko change kar dene ke bad bhi :point_up_2: massege aa rha hai .
code fine run kar rha tha eka ek errror aagya …

@Tradehull_Imran Sir
install libraries file me problem hai kya …

Thanks sir, but above code not worked because function not listed in tsl library, so I make a function
def get_option_chain(self, security_id, segment, expiry):
security_id = security_id
segment = segment
expiry = expiry

	try:
		option_chain = self.Dhan.option_chain(security_id,segment,expiry)
		df = pd.DataFrame(option_chain['data']['data'])
		return df
	except Exception as e:
		print(e)

,last_price,oc

18100.000000,24768.30078125,“{‘ce’: {‘greeks’: {‘delta’: 0, ‘theta’: 0, ‘gamma’: 0, ‘vega’: 0}, ‘implied_volatility’: 0, ‘last_price’: 0, ‘oi’: 0, ‘previous_close_price’: 0, ‘previous_oi’: 0, ‘previous_volume’: 0, ‘top_ask_price’: 0, ‘top_ask_quantity’: 0, ‘top_bid_price’: 0, ‘top_bid_quantity’: 0, ‘volume’: 0}, ‘pe’: {‘greeks’: {‘delta’: 0, ‘theta’: 0, ‘gamma’: 0, ‘vega’: 0}, ‘implied_volatility’: 8.105158988451517, ‘last_price’: 0, ‘oi’: 0, ‘previous_close_price’: 0, ‘previous_oi’: 0, ‘previous_volume’: 0, ‘top_ask_price’: 0, ‘top_ask_quantity’: 0, ‘top_bid_price’: 0, ‘top_bid_quantity’: 0, ‘volume’: 0}}”

18150.000000,24768.30078125,“{‘ce’: {‘greeks’: {‘delta’: 0, ‘theta’: 0, ‘gamma’: 0, ‘vega’: 0}, ‘implied_volatility’: 0, ‘last_price’: 0, ‘oi’: 0, ‘previous_close_price’: 0, ‘previous_oi’: 0, ‘previous_volume’: 0, ‘top_ask_price’: 0, ‘top_ask_quantity’: 0, ‘top_bid_price’: 0, ‘top_bid_quantity’: 0, ‘volume’: 0}, ‘pe’: {‘greeks’: {‘delta’: 0, ‘theta’: 0, ‘gamma’: 0, ‘vega’: 0}, ‘implied_volatility’: 8.036149211666558, ‘last_price’: 0, ‘oi’: 0, ‘previous_close_price’: 0, ‘previous_oi’: 0, ‘previous_volume’: 0, ‘top_ask_price’: 0, ‘top_ask_quantity’: 0, ‘top_bid_price’: 0, ‘top_bid_quantity’: 0, ‘volume’: 0}}”
but I am fail to make a proper data frame to look as use option chain it’s request you to please help me make a data frame

@Tradehull_Imran Sir for bulk orders like qty above freeze will this code work? or do i need some other.

buy_entry_orderid = tsl.order_placement(
        TRADING_SYMBOL, EXCHANGE, QTY, BUYING_LIMIT_PRICE, BUYING_TRIGGER, ORDER_TYPE, 'BUY', 'MIS'
    )

option_chain = dhan.option_chain(security_id,segment,expiry)

Initialize lists to store parsed data

data =

for strike, options in option_chain.items():
ce_data = options[‘ce’]
pe_data = options[‘pe’]

data.append({
    'strike': strike,
    'call_delta': ce_data['greeks']['delta'],
    'call_theta': ce_data['greeks']['theta'],
    'call_gamma': ce_data['greeks']['gamma'],
    'call_vega': ce_data['greeks']['vega'],
    'call_implied_volatility': ce_data['implied_volatility'],
    'call_last_price': ce_data['last_price'],
    'call_oi': ce_data['oi'],
    'put_delta': pe_data['greeks']['delta'],
    'put_theta': pe_data['greeks']['theta'],
    'put_gamma': pe_data['greeks']['gamma'],
    'put_vega': pe_data['greeks']['vega'],
    'put_implied_volatility': pe_data['implied_volatility'],
    'put_last_price': pe_data['last_price'],
    'put_oi': pe_data['oi'],
})

df = pd.DataFrame(data)
@parveen_chugh - Sharing sample code snippet. Should give you an idea to enhance the function from here.

1 Like

Hi Imran Sir,

Getting error.
D:\my_applications\my_algo\Candle_Theory_Algo>py “2 candle theory Algo V1.py”
Traceback (most recent call last):
File “D:\my_applications\my_algo\Candle_Theory_Algo\2 candle theory Algo V1.py”, line 1, in
import pdb
File “D:\my_applications\python\Lib\site-packages_pdbpp_path_hack\pdb.py”, line 5, in
exec(compile(f.read(), pdb_path, ‘exec’))
~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “D:\my_applications\python\Lib\site-packages\pdb.py”, line 23, in
from fancycompleter import Completer, ConfigurableClass, Color
File “D:\my_applications\python\Lib\site-packages\fancycompleter.py”, line 7, in
import rlcompleter
File “D:\my_applications\python\Lib\rlcompleter.py”, line 212, in
import readline
File “D:\my_applications\python\Lib\site-packages\readline.py”, line 34, in
rl = Readline()
File “D:\my_applications\python\Lib\site-packages\pyreadline\rlmain.py”, line 422, in init
BaseReadline.init(self)
~~~~~~~~~~~~~~~~~~~~~^^^^^^
File “D:\my_applications\python\Lib\site-packages\pyreadline\rlmain.py”, line 62, in init
mode.init_editing_mode(None)
~~~~~~~~~~~~~~~~~~~~~~^^^^^^
File “D:\my_applications\python\Lib\site-packages\pyreadline\modes\emacs.py”, line 633, in init_editing_mode
self._bind_key(‘space’, self.self_insert)
~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “D:\my_applications\python\Lib\site-packages\pyreadline\modes\basemode.py”, line 162, in _bind_key
if not callable(func):
~~~~~~~~^^^^^^
File “D:\my_applications\python\Lib\site-packages\pyreadline\py3k_compat.py”, line 8, in callable
return isinstance(x, collections.Callable)
^^^^^^^^^^^^^^^^^^^^
AttributeError: module ‘collections’ has no attribute ‘Callable’

@Tradehull_Imran
Hi Imran, How to backtest the algo startegy and for how many past data we can test. Please share the method to backtest the strategy.

Hi sir

please Solve this problem
D:\algo\Lab test\Dhan codebase>py buy_sell.py
Codebase Version 2.3 : Solved - ATM issues
-----Logged into Dhan-----
reading existing file all_instrument 2024-12-15.csv
Got the instrument file
AVAILABLE BALANCE = 95.94
BUY 19:55:14.425103 True True True True True BUY ENTRY CONDITIONS 15:10:00
SELL 19:55:14.425103 False False True True False SELL ENTRY CONDITIONS 15:10:00

CALL BUY SIGNAL FORMED
exception got in ce_pe_option_df ‘<’ not supported between instances of ‘int’ and ‘str’
Enter valid Script Name
'Got exception in place_order as ‘NoneType’ object has no attribute ‘upper’
Error at get_executed_price as Check the order id, Error as None
Traceback (most recent call last):
File “D:\algo\Lab test\Dhan codebase\Dhan_Tradehull_V2.py”, line 1162, in get_executed_price
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 “buy_sell.py”, line 143, in
buy_condition(index_name)
File “buy_sell.py”, line 72, in buy_condition
trade_info[‘entry_price’] = tsl.get_executed_price(orderid=trade_info[‘entry_orderid’])
File “D:\algo\Lab test\Dhan codebase\Dhan_Tradehull_V2.py”, line 1177, in get_executed_price
‘data’:response,
UnboundLocalError: local variable ‘response’ referenced before assignment

Hi @Tradehull_Imran,

any update on this?

Thanks @AmitKAswani but this code also getting error

string indices must be integers, not ‘str’

Dhan_websocket.py is asking for subscription code for Dhanfeed at line 78

@parveen_chugh - That was just a sample code to show how to handle the data structure.

I quickly created a test class for generating the option chain. Please modify as per your requirement.

class Test:

@staticmethod
def raw_option_chain(_securityId,_exchange_segement,_expiry_date):
     _rawOC = {}
     _rawOC = dhan.option_chain(_securityId,_exchange_segement,_expiry_date)
     return _rawOC    


@staticmethod    
def option_chain(_rawOC):
    _option_chain = _rawOC.get('data', {}).get('data', {}).get('oc', {})

    # Initialize a list to store parsed data
    _data = []
    
    # Loop through the option chain dictionary
    for _strike, _options in _option_chain.items():
        try:
            _strike_price = float(_strike)  
            _ce_data = _options.get('ce', {})  # Safely get 'ce' data
            _pe_data = _options.get('pe', {})  # Safely get 'pe' data
    
            # Append the parsed data to the list
            _data.append({
                'strike': _strike_price,
                'call_delta': _ce_data.get('greeks', {}).get('delta', None),
                'call_theta': _ce_data.get('greeks', {}).get('theta', None),
                'call_gamma': _ce_data.get('greeks', {}).get('gamma', None),
                'call_vega': _ce_data.get('greeks', {}).get('vega', None),
                'call_implied_volatility': _ce_data.get('implied_volatility', None),
                'call_last_price': _ce_data.get('last_price', None),
                'call_oi': _ce_data.get('oi', None),
                'put_delta': _pe_data.get('greeks', {}).get('delta', None),
                'put_theta': _pe_data.get('greeks', {}).get('theta', None),
                'put_gamma': _pe_data.get('greeks', {}).get('gamma', None),
                'put_vega': _pe_data.get('greeks', {}).get('vega', None),
                'put_implied_volatility': _pe_data.get('implied_volatility', None),
                'put_last_price': _pe_data.get('last_price', None),
                'put_oi': _pe_data.get('oi', None),
            })
        except Exception as e:
            print(f"Error processing strike {_strike}: {e}")
    
    # Convert the list of dictionaries into a Pandas DataFrame
    _df = pd.DataFrame(_data)
    
    # Print the resulting DataFrame
    print(_df)

_rawOC = Test.raw_option_chain(13,“IDX_I”,“2024-12-19”)
Test.option_chain(_rawOC)

1 Like