Learn Algo Trading with Python | Codes | Youtube Series

Hi @Vasili_Prasad

Good question on F string

lets use an example

entry_time  = '2023-07-20 09:15:00+05:30'
qty         = 25
buy_sell    = 'BUY_CE'
entry_price = 50
sl_price    = 25


# without using F string, its complex to make print statements
print("I want to buy at", entry_time, " with qty: ", qty, " buy_sell: ", buy_sell, " entry_price: ", entry_price, " sl_price: ", sl_price)


# using F string, its easy to make print statements
# inside curly brackets {} we keep variables in f string
print(f"I want to buy at {entry_time} with qty: {qty} buy_sell: {buy_sell} entry_price: {entry_price} sl_price: {sl_price}")

so basically, F string makes code more readable

Hi @Himansshu_Joshi

Solution link : Learn Algo Trading with Python | Codes | Youtube Series - #1365 by Tradehull_Imran

AI AT WORK :fire:

3 Likes

sir modify nahi kar raha he ,

Using AI in the software itself , Great Sir, Very Advance Feature :saluting_face:

1 Like

@Tradehull_Imran Hi sir, a very easy thing but i am not getting it, the thing i want is to extract leg name through order id , what will be the code?

AS I can see everybody is enough curious and 147 active users


answer is

api = dhanhq
required_people_intrested = (100 // 147)
url = "https://madefortrade.in/t/learn-algo-trading-with-python-codes-youtube-series/32718"
people_intrested = madefortrade.get_live_data(url)
people_intrested  = 147

if people_intrested > required_people_intrested:
	print("🔴 BUILD ALGO LIVE SESSION ON YOUTUBE")
	print("🔴 LIVE QUESTIONS AND ANSWER IMPLEMENTATION")
else:
	print("Wait ⏳")


print("SEND ME YOUR ANSWER IN CODE")

OUTPUT :
:red_circle: BUILD ALGO LIVE SESSION ON YOUTUBE
:red_circle: LIVE QUESTIONS AND ANSWER IMPLEMENTATION

SEND ME YOUR ANSWER IN CODE

I know it’s over. we joined and really enjoyed
:smiling_face: :smiling_face: :hugs: :hugs: :pray:t2:

2 Likes

@Tradehull_Imran Sir Today I am just doing practical of
9. Session9- 3rd Live Algo Version 2

Where below file is working fine as expected

Pre Market Scanner.py

but when I am trying to run

Breakout Algo on Stock Options.py

getting error and It’s trying to read

all_instrument 2024-12-08.csv

which is not exist at all.

Tomorrow I will try it again in live market

watch this @Tradehull_Imran sir’s video How use external library and find out any candlestick pattern easily by python code :pray:t2: :pray:t2: :pray:t2: :100: :boom:

2 Likes

2-Candle Theory: The Ultimate Trading Algorithm || @DhanHQ @OptionsScalping

@Tradehull_Imran sir,
I have just tested it. I think it’s working file

One question Here also it is showing

reading existing file all_instrument 2024-12-09.csv

which is not present at all

good morning @Tradehull_Imran Sir

rsi ke sath vwma ko kaise code kre…(exmple - rsi > rsivwma or rsi crossover rsivwma)(vwma period 60 ke sath)
Please help

Very Good Morning sir.
And Thank you very much sir.

VBR Prasad

Sir the following code line, showing error, Please guide.

ltp_data = tsl.get_ltp_data(names=‘BANKNIFTY’, ‘NIFTY’, ‘CRUDEOIL’, ‘RELIANCE’,)
for script_name,ltp in ltp_data.items():
print(script_name,ltp)

Error in cmd prompt:

Syntax Error: positional argument follows keyword argument

Upward arrow is indicated at N of “NIFTY”,

How to resolve sir.

Hi @Himansshu_Joshi
Do run the code in live market, and do send error if any.
Also I have added pseudocode, so do make the necessary adjustments

Hi @Himansshu_Joshi

I am bit unclear on the question. do send it in detail.
In the code both legs buy_entry_orderid and stoploss_orderid are anyways managed seperately.

Hi @Subhajitpanja

  1. Do expand the dependencies by clicking >

  2. Also go in the folder manually though Windows File Explorer
    to /ALGORITHIM_HQ/2. 2 Candle Theory Algo/Dependencies/.abc.py

and check if all_instrument 2024-12-09.csv is present there.

mostly the instrument file should be there, else its not possible for code to read it

Hi @vinay_kumaar

use this code, for overlapping indicators

chart = tsl.get_historical_data(tradingsymbol = 'ACC',exchange = 'NSE',timeframe="5")
chart['rsi'] = talib.RSI(chart['close'], timeperiod=14)
chart['pv'] = chart['rsi'] * chart['volume']
chart['rsivwma'] = chart['pv'].rolling(10).mean() / chart['volume'].rolling(10).mean()

Hi @Vasili_Prasad

we need to pass names in a list format to get the ltp

use below code

(Pdb++) tsl.get_ltp_data(names=['BANKNIFTY', 'NIFTY', 'CRUDEOIL', 'RELIANCE'])
{'NIFTY': 24662.1, 'BANKNIFTY': 53721.15, 'CRUDEOIL': 5742, 'RELIANCE': 1307.75} ... output

@Tradehull_Imran sir
Today I have tried again

# https://ta-lib.github.io/ta-lib-python/
# https://www.notion.so/TradeHull-Dhan-Codebase-76b32fa814e64aea843e14a148854214#efa40986725341e6bfa9ad6fcfc10a6d


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

client_code = ""
token_id    = ""


tsl = Tradehull(client_code,token_id)



available_balance = tsl.get_balance()
leveraged_margin  = available_balance*5
max_trades = 1
per_trade_margin = (leveraged_margin/max_trades)
max_loss = (available_balance*1)/100*-1

watchlist = ['TATAMOTORS']
traded_wathclist = []
tarde_info = {'Direction': 'buy', 'level': 819}


while True:

	live_pnl = tsl.get_live_pnl()
	current_time = datetime.datetime.now().time()

	if current_time < datetime.time(9, 30):
		print("wait for market to start", 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 over, Bye Bye see you tomorrow", current_time)
		break

	for stock_name in watchlist:
		time.sleep(0.2)
		print(f"Scaning {stock_name}")


		chart_5            = tsl.get_historical_data(tradingsymbol = stock_name, exchange = 'NSE',timeframe="5")       # Upgraded 5 minute chart according to Dhan_Tradehull_V2
		cc_5               = chart_5.iloc[-1]   # pandas
		no_repeat_order    = stock_name not in traded_wathclist


		if (tarde_info['Direction'] == "buy") and no_repeat_order:
			cc_volume      = cc_5['volume']
			average_volume = chart_5['volume'].mean()

			breakout_c1    = cc_5['close'] > tarde_info['level']
			breakout_c2    = cc_volume > 2*average_volume
			breakout_c3    = cc_5['open'] != cc_5['close']

			atm_ce_name, atm_pe_name, strike = tsl.ATM_Strike_Selection(stock_name,'09-12-2024')  #atm_ce_name, pe_strike, ce_OTM_price, pe_OTM_price = tsl.OTM_Strike_Selection(stock_name,'08-08-2024',3)


			atm_ce_ltp     = tsl.get_ltp_data(names = [atm_ce_name])[atm_ce_name]
			lot_size       = tsl.get_lot_size(atm_ce_name)
			entry_price    = round((atm_ce_ltp*1.02),1)

			sl_price       = round((atm_ce_ltp*0.8),1)


			entry_orderid  = tsl.order_placement(atm_ce_name,'NFO', lot_size, entry_price, 0, 'LIMIT', 'BUY', 'MIS')
			sl_orderid     = tsl.order_placement(atm_ce_name,'NFO', lot_size, 0, sl_price, 'STOPMARKET', 'SELL', 'MIS')

			traded_wathclist.append(stock_name)







but getting same error

PS C:\Users\Subhajit Panja\Documents\Algorithim_HQ> & "c:/Users/Subhajit Panja/Documents/Algorithim_HQ/.venv/Scripts/python.exe" "c:/Users/Subhajit Panja/Documents/Algorithim_HQ/3rd live Algo/Breakout Algo on Stock Options.py"
Codebase Version 2.1
-----Logged into Dhan-----
reading existing file all_instrument 2024-12-09.csv
Got the instrument file
Scaning TATAMOTORS
Traceback (most recent call last):
  File "c:\Users\Subhajit Panja\Documents\Algorithim_HQ\3rd live Algo\Dhan_Tradehull_V2.py", line 514, in ATM_Strike_Selection
    closest_index = ce_df['diff'].idxmin()
  File "C:\Users\Subhajit Panja\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\series.py", line 2460, in idxmin
    i = self.argmin(axis, skipna, *args, **kwargs)  # type: ignore[arg-type]
  File "C:\Users\Subhajit Panja\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\base.py", line 742, in argmin
    return nanops.nanargmin(  # type: ignore[return-value]
  File "C:\Users\Subhajit Panja\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\nanops.py", line 96, in _f
    return f(*args, **kwargs)
  File "C:\Users\Subhajit Panja\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\nanops.py", line 1193, 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\Subhajit Panja\Documents\Algorithim_HQ\3rd live Algo\Dhan_Tradehull_V2.py", line 514, in ATM_Strike_Selection
    closest_index = ce_df['diff'].idxmin()
  File "C:\Users\Subhajit Panja\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\series.py", line 2460, in idxmin
    i = self.argmin(axis, skipna, *args, **kwargs)  # type: ignore[arg-type]
  File "C:\Users\Subhajit Panja\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\base.py", line 742, in argmin
    return nanops.nanargmin(  # type: ignore[return-value]
  File "C:\Users\Subhajit Panja\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\nanops.py", line 96, in _f
    return f(*args, **kwargs)
  File "C:\Users\Subhajit Panja\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\nanops.py", line 1193, 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\Subhajit Panja\AppData\Local\Programs\Python\Python38\lib\logging\__init__.py", line 1081, in emit
    msg = self.format(record)
  File "C:\Users\Subhajit Panja\AppData\Local\Programs\Python\Python38\lib\logging\__init__.py", line 925, in format
    return fmt.format(record)
  File "C:\Users\Subhajit Panja\AppData\Local\Programs\Python\Python38\lib\logging\__init__.py", line 664, in format
    record.message = record.getMessage()
  File "C:\Users\Subhajit Panja\AppData\Local\Programs\Python\Python38\lib\logging\__init__.py", line 369, in getMessage
    msg = msg % self.args
TypeError: not all arguments converted during string formatting
Call stack:
  File "c:/Users/Subhajit Panja/Documents/Algorithim_HQ/3rd live Algo/Breakout Algo on Stock Options.py", line 64, in <module>
    atm_ce_name, atm_pe_name, strike = tsl.ATM_Strike_Selection(stock_name,'09-12-2024')  #atm_ce_name, pe_strike, ce_OTM_price, pe_OTM_price = tsl.OTM_Strike_Selection(stock_name,'08-08-2024',3)
  File "c:\Users\Subhajit Panja\Documents\Algorithim_HQ\3rd live Algo\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'),)
exception got in ce_pe_option_df attempt to get argmin of an empty sequence
None
Traceback (most recent call last):
  File "c:/Users/Subhajit Panja/Documents/Algorithim_HQ/3rd live Algo/Breakout Algo on Stock Options.py", line 67, in <module>
    atm_ce_ltp     = tsl.get_ltp_data(names = [atm_ce_name])[atm_ce_name]
KeyError: None

updated below things

atm_ce_name, atm_pe_name, strike = tsl.ATM_Strike_Selection(stock_name,'09-12-2024')


watchlist = [‘TATAMOTORS’]
tarde_info = {‘Direction’: ‘buy’, ‘level’: 819}

@Tradehull_Imran sir here also same