Hi @Tradehull_Imran, Sharing the code of main file and error received below. Unable to attach Dhan_Tradehull_v2 as its crossing the word limit allowed in this forum
-----main file-----
import pdb
import pandas as pd
import talib
import time
import datetime
import warnings,sys
warnings.filterwarnings("ignore")
path = r'C:/Users/krish/OneDrive/Documents/Krishna/2 Areas/Finance/Stock Market/Trading/Trading Courses/Development/AlgoTrading/Dhan/DhanAlgoTrading'
sys.path.insert(0, path)
import credentials as cred
from Dhan_Tradehull_V2 import Tradehull
import PreMarketScanner as pms
# ---------------Basic setup for dhan login & Defining Constants------------------------
client_code = cred.CLIENT_ID
token_id = cred.ACCESS_TOKEN
tsl = Tradehull(client_code,token_id)
available_balance = tsl.get_balance()
# leveraged_margin = available_balance*5
max_trades = 5
per_trade_margin = (available_balance/max_trades/5)
max_loss = -available_balance/100
EXPIRY ='28-11-2024'
LOT_SIZE = 1
# ---------------------------------------------------------------------------------------
trade_info = pms.premarketscan()
traded_watchlist = []
trade_dict = {}
while True:
live_pnl = tsl.get_live_pnl()
current_time = datetime.datetime.now().time()
if current_time < datetime.time(9, 30):
print("Market yet to open", current_time)
continue
if (current_time > datetime.time(15, 15)) or (live_pnl < max_loss):
# I_want_to_trade_no_more = tsl.kill_switch('ON') # removed Kill swtich as it may get accidenyl hit while Testing and block all future order placement
order_details = tsl.cancel_all_orders()
print("Market is closed!", current_time)
break
for idx,row in trade_info.iterrows():
time.sleep(0.2)
print(f"Scanning {row['script']}")
chart_5 = tsl.get_historical_data(tradingsymbol = row['script'], exchange = 'NSE',timeframe="5") # Upgraded 5 minute chart according to Dhan_Tradehull_V2
cc_5 = chart_5.iloc[-1] # pandas
cc_volume = cc_5['volume']
average_volume = chart_5['volume'].mean()
no_repeat_order = row['script'] not in traded_watchlist
atm_ce_name, atm_pe_name, strike = tsl.ATM_Strike_Selection(row['script'],EXPIRY) #atm_ce_name, pe_strike, ce_OTM_price, pe_OTM_price = tsl.OTM_Strike_Selection(stock_name,'08-08-2024',3)
if (idx == "buy") and no_repeat_order: #trade_info['Direction']
breakout_c1 = cc_5['close'] > row['level']
breakout_c2 = cc_volume > 2*average_volume
breakout_c3 = cc_5['open'] != cc_5['close']
atm_ce_ltp = tsl.get_ltp_data(names = [atm_ce_name])[atm_ce_name]
lot_size = tsl.get_lot_size(atm_ce_name)
ce_entry_price = round((atm_ce_ltp*1.02),1)
ce_sl_price = round((atm_ce_ltp*0.8),1)
trade_dict['stock_name'] = row['script']
trade_dict['direction'] = 'buy'
trade_dict['expiry'] = EXPIRY
trade_dict['option'] = 'ce'
trade_dict['lot_size'] = lot_size
trade_dict['buy_price'] = ce_entry_price
trade_dict['sl_price'] = ce_sl_price
trade_dict['sell_price'] = 0
traded_watchlist.append(row['script'])
elif (idx == "sell") and no_repeat_order: #trade_info['Direction']
breakout_c1 = cc_5['close'] < row['level']
breakout_c2 = cc_volume > 2*average_volume
breakout_c3 = cc_5['open'] != cc_5['close']
atm_pe_ltp = tsl.get_ltp_data(names = [atm_pe_name])[atm_pe_name]
lot_size = tsl.get_lot_size(atm_pe_name)
pe_entry_price = round((atm_pe_ltp*0.98),1)
pe_sl_price = round((atm_pe_ltp*1.2),1)
trade_dict['stock_name'] = row['script']
trade_dict['direction'] = 'buy'
trade_dict['expiry'] = EXPIRY
trade_dict['option'] = 'pe'
trade_dict['lot_size'] = lot_size
trade_dict['buy_price'] = pe_entry_price
trade_dict['sl_price'] = pe_sl_price
trade_dict['sell_price'] = 0
traded_watchlist.append(row['script'])```
----Error details -----------------
Traceback (most recent call last):
File “C:\Users/krish/OneDrive/Documents/Krishna/2 Areas/Finance/Stock Market/Trading/Trading Courses/Development/AlgoTrading/Dhan/DhanAlgoTrading\Dhan_Tradehull_V2.py”, line 514, in ATM_Strike_Selection
closest_index = ce_df[‘diff’].idxmin()
^^^^^^^^^^^^^^^^^^^^^^
File “c:\Users\krish\anaconda3\Lib\site-packages\pandas\core\series.py”, line 2561, in idxmin
i = self.argmin(axis, skipna, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “c:\Users\krish\anaconda3\Lib\site-packages\pandas\core\base.py”, line 785, in argmin
result = nanops.nanargmin(delegate, skipna=skipna)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “c:\Users\krish\anaconda3\Lib\site-packages\pandas\core\nanops.py”, line 1188, in nanargmin
result = values.argmin(axis) # type: ignore[var-annotated]
^^^^^^^^^^^^^^^^^^^
ValueError: attempt to get argmin of an empty sequence
— Logging error —
Traceback (most recent call last):
File “C:\Users/krish/OneDrive/Documents/Krishna/2 Areas/Finance/Stock Market/Trading/Trading Courses/Development/AlgoTrading/Dhan/DhanAlgoTrading\Dhan_Tradehull_V2.py”, line 514, in ATM_Strike_Selection
closest_index = ce_df[‘diff’].idxmin()
^^^^^^^^^^^^^^^^^^^^^^
File “c:\Users\krish\anaconda3\Lib\site-packages\pandas\core\series.py”, line 2561, in idxmin
i = self.argmin(axis, skipna, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “c:\Users\krish\anaconda3\Lib\site-packages\pandas\core\base.py”, line 785, in argmin
result = nanops.nanargmin(delegate, skipna=skipna)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “c:\Users\krish\anaconda3\Lib\site-packages\pandas\core\nanops.py”, line 1188, in nanargmin
result = values.argmin(axis) # type: ignore[var-annotated]
^^^^^^^^^^^^^^^^^^^
ValueError: attempt to get argmin of an empty sequence
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File “c:\Users\krish\anaconda3\Lib\logging_init_.py”, line 1110, in emit
msg = self.format(record)
^^^^^^^^^^^^^^^^^^^
File “c:\Users\krish\anaconda3\Lib\logging_init_.py”, line 953, in format
return fmt.format(record)
^^^^^^^^^^^^^^^^^^
File “c:\Users\krish\anaconda3\Lib\logging_init_.py”, line 687, in format
record.message = record.getMessage()
^^^^^^^^^^^^^^^^^^^
File “c:\Users\krish\anaconda3\Lib\logging_init_.py”, line 377, in getMessage
msg = msg % self.args
^~~~~~~
TypeError: not all arguments converted during string formatting
Call stack:
File “”, line 198, in _run_module_as_main
File “”, line 88, in _run_code
File “c:\Users\krish\anaconda3\Lib\site-packages\ipykernel_launcher.py”, line 17, in
app.launch_new_instance()
File “c:\Users\krish\anaconda3\Lib\site-packages\traitlets\config\application.py”, line 992, in launch_instance
app.start()
File “c:\Users\krish\anaconda3\Lib\site-packages\ipykernel\kernelapp.py”, line 701, in start
self.io_loop.start()
File “c:\Users\krish\anaconda3\Lib\site-packages\tornado\platform\asyncio.py”, line 195, in start
self.asyncio_loop.run_forever()
File “c:\Users\krish\anaconda3\Lib\asyncio\windows_events.py”, line 321, in run_forever
super().run_forever()
File “c:\Users\krish\anaconda3\Lib\asyncio\base_events.py”, line 607, in run_forever
self._run_once()
File “c:\Users\krish\anaconda3\Lib\asyncio\base_events.py”, line 1922, in _run_once
handle._run()
File “c:\Users\krish\anaconda3\Lib\asyncio\events.py”, line 80, in _run
self._context.run(self._callback, *self._args)
File “c:\Users\krish\anaconda3\Lib\site-packages\ipykernel\kernelbase.py”, line 534, in dispatch_queue
await self.process_one()
File “c:\Users\krish\anaconda3\Lib\site-packages\ipykernel\kernelbase.py”, line 523, in process_one
await dispatch(*args)
File “c:\Users\krish\anaconda3\Lib\site-packages\ipykernel\kernelbase.py”, line 429, in dispatch_shell
await result
File “c:\Users\krish\anaconda3\Lib\site-packages\ipykernel\kernelbase.py”, line 767, in execute_request
reply_content = await reply_content
File “c:\Users\krish\anaconda3\Lib\site-packages\ipykernel\ipkernel.py”, line 429, in do_execute
res = shell.run_cell(
File “C:\Users\krish\AppData\Local\Temp\ipykernel_30692\1532818857.py”, line 29, in wrapper
result = old_func(*args, **kwargs)
File “c:\Users\krish\anaconda3\Lib\site-packages\ipykernel\zmqshell.py”, line 549, in run_cell
return super().run_cell(*args, **kwargs)
File “c:\Users\krish\anaconda3\Lib\site-packages\IPython\core\interactiveshell.py”, line 3051, in run_cell
result = self._run_cell(
File “c:\Users\krish\anaconda3\Lib\site-packages\IPython\core\interactiveshell.py”, line 3106, in _run_cell
result = runner(coro)
File “c:\Users\krish\anaconda3\Lib\site-packages\IPython\core\async_helpers.py”, line 129, in pseudo_sync_runner
coro.send(None)
File “c:\Users\krish\anaconda3\Lib\site-packages\IPython\core\interactiveshell.py”, line 3311, in run_cell_async
has_raised = await self.run_ast_nodes(code_ast.body, cell_name,
File “c:\Users\krish\anaconda3\Lib\site-packages\IPython\core\interactiveshell.py”, line 3493, in run_ast_nodes
if await self.run_code(code, result, async=asy):
File “c:\Users\krish\anaconda3\Lib\site-packages\IPython\core\interactiveshell.py”, line 3553, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File “”, line 64, in
atm_ce_name, atm_pe_name, strike = tsl.ATM_Strike_Selection(row[‘script’],EXPIRY) #atm_ce_name, pe_strike, ce_OTM_price, pe_OTM_price = tsl.OTM_Strike_Selection(stock_name,‘08-08-2024’,3)
File “C:\Users/krish/OneDrive/Documents/Krishna/2 Areas/Finance/Stock Market/Trading/Trading Courses/Development/AlgoTrading/Dhan/DhanAlgoTrading\Dhan_Tradehull_V2.py”, line 541, in ATM_Strike_Selection
self.logger.exception("Got exception in ce_pe_option_df ", e)
Message: 'Got exception in ce_pe_option_df ’
Arguments: (ValueError(‘attempt to get argmin of an empty sequence’),)