Learn Algo Trading with Python | Codes | Youtube Series

H @babji3

use below pseudocode, to maintain reward_risk_ratio


import pdb
import time
import datetime
import traceback
from Dhan_Tradehull_V2 import Tradehull
import pandas as pd
from pprint import pprint
import talib
import pandas_ta as pta
import pandas_ta as ta
import warnings

warnings.filterwarnings("ignore")



# ---------------for dhan login ----------------
client_code = "1102790337"
token_id    = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJkaGFuIiwicGFydG5lcklkIjoiIiwiZXhwIjoxNzMyOTQzNzg5LCJ0b2tlbkNvbnN1bWVyVHlwZSI6IlNFTEYiLCJ3ZWJob29rVXJsIjoiIiwiZGhhbkNsaWVudElkIjoiMTEwMjc5MDMzNyJ9.hk6DAzd9YWb06hgFX9u7_Omq0srX2ofsgOp1qf2V7DIMT5OfVGN2IJds3MumsMh3wVon--TJSB9dmm5P6T3KWQ"


tsl = Tradehull(client_code,token_id)

traded = "no"
trade_info = {"options_name":None, "qty":None, "sl":None, "CE_PE":None}
reward_risk_ratio = 3


while True:

	current_time = datetime.datetime.now()

	index_chart  = tsl.get_historical_data(tradingsymbol='NIFTY DEC FUT', exchange='NFO', timeframe="5")
	time.sleep(5)
	index_ltp    = tsl.get_ltp_data(names = ['NIFTY DEC FUT'])['NIFTY DEC FUT']

	if (index_chart.empty):
		time.sleep(60)
		continue


	# rsi    ------------------------ apply indicators
	index_chart['rsi'] = talib.RSI(index_chart['close'], timeperiod=14)

	# vwap
	index_chart.set_index(pd.DatetimeIndex(index_chart['timestamp']), inplace=True)
	index_chart['vwap'] = pta.vwap(index_chart['high'] , index_chart['low'], index_chart['close'] , index_chart['volume'])

	# Supertrend
	indi = ta.supertrend(index_chart['high'], index_chart['low'], index_chart['close'], 10, 2)
	index_chart = pd.concat([index_chart, indi], axis=1, join='inner')


	# vwma
	index_chart['pv'] = index_chart['close'] * index_chart['volume']
	index_chart['vwma'] = index_chart['pv'].rolling(20).mean() / index_chart['volume'].rolling(20).mean()

	# volume
	volume = 50000

	first_candle   = index_chart.iloc[-3]
	second_candle  = index_chart.iloc[-2]
	running_candle = index_chart.iloc[-1]


	# ---------------------------- BUY ENTRY CONDITIONS ----------------------------
	bc1 = first_candle['close'] > first_candle['vwap']                # First Candle close is above VWAP
	bc2 = first_candle['close'] > first_candle['SUPERT_10_2.0']       # First Candle close is above Supertrend 
	bc3 = first_candle['close'] > first_candle['vwma']                # First Candle close is above VWMA
	bc4 = first_candle['rsi'] < 80                                    # First candle RSI < 80	
	bc5 = second_candle['volume'] > 50000                             # Second candle Volume should be greater than 50,000 for Nifty and above 125,000 for Bank Nifty
	bc6 = traded == "no"
	bc7 = index_ltp > first_candle['low']
	print(f"BUY \t {current_time} \t {bc1} \t {bc2} \t {bc3} \t {bc4} \t {bc5} \t {bc6} \t {bc7} \t first_candle {str(first_candle['timestamp'].time())}")


	# ---------------------------- SELL ENTRY CONDITIONS ----------------------------
	sc1 = first_candle['close'] < first_candle['vwap']                # First Candle close is below VWAP
	sc2 = first_candle['close'] < first_candle['SUPERT_10_2.0']       # First Candle close is below Supertrend 
	sc3 = first_candle['close'] < first_candle['vwma']                # First Candle close is below VWMA
	sc4 = first_candle['rsi'] > 20                                    # First candle RSI < 80	
	sc5 = second_candle['volume'] > 50000                             # Second candle Volume should be greater than 50,000 for Nifty and above 125,000 for Bank Nifty
	sc6 = traded == "no"
	sc7 = index_ltp < first_candle['high']
	print(f"SELL \t {current_time} \t {sc1} \t {sc2} \t {sc3} \t {sc4} \t {sc5} \t {sc6} \t {sc7} \t first_candle {str(first_candle['timestamp'].time())} \n")



	if bc1 and bc2 and bc3 and bc4 and bc5 and bc6 and bc7:
		print("Buy Signal Formed")

		ce_name, pe_name, ce_strike, pe_strike = tsl.OTM_Strike_Selection('NIFTY','05-12-2024',4)
		lot_size                   = tsl.get_lot_size(ce_name)*1
		entry_orderid              = tsl.order_placement(ce_name,'NFO', lot_size, 0, 0, 'MARKET', 'BUY', 'MIS')
		traded                     = "yes"
		trade_info['options_name'] = ce_name
		trade_info['qty']          = lot_size
		trade_info['sl']           = first_candle['low']

		sl_points                  = first_candle['close'] - first_candle['low']
		trade_info['target']       = first_candle['close'] + reward_risk_ratio*sl_points
		trade_info['CE_PE']        = "CE"



	if sc1 and sc2 and sc3 and sc4 and sc5 and sc6 and sc7:
		print("Sell Signal Formed")

		ce_name, pe_name, ce_strike, pe_strike = tsl.OTM_Strike_Selection('NIFTY','05-12-2024',4)
		lot_size                   = tsl.get_lot_size(pe_name)*1
		entry_orderid              = tsl.order_placement(pe_name,'NFO', lot_size, 0, 0, 'MARKET', 'BUY', 'MIS')
		traded                     = "yes"
		trade_info['options_name'] = pe_name
		trade_info['qty']          = lot_size
		trade_info['sl']           = first_candle['high']

		sl_points                  = first_candle['high'] - first_candle['close']
		trade_info['target']       = first_candle['close'] - reward_risk_ratio*sl_points	
		trade_info['CE_PE']        = "PE"



	# ---------------------------- check for exit SL/TG

	if traded == "yes":

		long_position  = trade_info['CE_PE'] == "CE"
		short_position = trade_info['CE_PE'] == "PE"


		if long_position:
			sl_hit          = index_ltp < trade_info['sl']
			trailing_tg_hit = index_ltp < running_candle['SUPERT_10_2.0']   # this is a trailing target, by supertrend
			tg_hit          = index_ltp > trade_info['target']

			if sl_hit or trailing_tg_hit or tg_hit:
				print("Order Exited", trade_info)
				exit_orderid        = tsl.order_placement(trade_info['options_name'],'NFO', trade_info['qty'], 0, 0, 'MARKET', 'SELL', 'MIS')
				pdb.set_trace()





		if short_position:
			sl_hit          = index_ltp > trade_info['sl']
			trailing_tg_hit = index_ltp > running_candle['SUPERT_10_2.0']   # this is a trailing target, by supertrend
			tg_hit          = index_ltp < trade_info['target']

			if sl_hit or trailing_tg_hit or tg_hit:
				print("Order Exited", trade_info)
				exit_orderid        = tsl.order_placement(trade_info['options_name'],'NFO', trade_info['qty'], 0, 0, 'MARKET', 'SELL', 'MIS')
				pdb.set_trace()
















# trade_info = {
# 				'CE_PE': 'PE',
# 				'options_name': 'NIFTY 21 DEC 23350 PUT',
# 				'qty': 25,
# 				'sl': 23357.95
# 			}



2 Likes

Hi @Azad_Gavit

can you send the code that you are using,

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

Hi @Swapnil_Sutar

  1. Yes we do need to buy historical data

  2. Also we have upgraded to get_historical_data, and now get_intraday_data will not be used in future
    apply this one : Learn Algo Trading with Python | Codes | Youtube Series - #952 by Tradehull_Imran

  3. use this latest codebase file : Dhan_Tradehull_V2.py - Google Drive

1 Like

Hi @Kishore007

For Backtesting I am thinking of a new structure. [Open Source Backtesting]
Let me know which should we backtest first.

See : https://youtu.be/84zPTx357N0?si=3Om8I5H6lzRUfXZj

Also I am looking for a minimum momentum of 50 votes to start on this.

  • Options Selling Backtesting
  • Option Buying Backtesting
  • Equity Backtesting
0 voters

Also do invite your trades friends :people_holding_hands::couple::two_men_holding_hands::two_women_holding_hands:

5 Likes

Hi @HJS_DVK

yes this issue was resolved

solution link: Learn Algo Trading with Python | Codes | Youtube Series - #827 by Tradehull_Imran

use latest codebase : Dhan_Tradehull_V2.py - Google Drive

Updated codebase explanation : https://www.youtube.com/watch?v=HLiEpNZSD80

Hi @Subhajitpanja

I am not clear with this line

So we can take easily one more near accurate steps with considering **ask bid spread**

can you please rephrase the question.

Hi @virender_singh

we can use margin calculator in this case

use code


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)

Hi @Everyone
Happy New Year

3 Likes

Sir,
After creating any strategy, before buy/sell
(Or Putting Market or Limit price directly
Can we check buyer and seller market depth with help of ask and bid price with there quantity to check where buyer or seller more aggressive

Suppose I want buy 4 lot or 40 quantity with a specific Limit price

But from ask and bid section
I can see buyer seller condition with there buying and selling qty


So we take trade with more confidence even for stoploss also

@Tradehull_Imran sir I am thinking just below one. How we can use that to our algo

2 Likes

Hi @Subhajitpanja

API supports Level-2 marketdepth as of now. (Top5 bid ask)

we can gauge current moment aggressive of buyers/sellers from this one

quote_data = tsl.get_quote(names = 'ACC')
buyers     = pd.DataFrame(quote_data['ACC']['depth']['buy'])
sellers    = pd.DataFrame(quote_data['ACC']['depth']['sell'])

2 Likes

OK sir got that. Hope to near future @Dhan ( @Hardik ) will take care to make it available more deeper market depth (like 20th level data) to Dhan HQ API

Hello @Tradehull_Imran,

I am not able to send Telegram alerts in algo. please help.

message = “Trial telegram message”
tsl.send_telegram_alert(message=message,receiver_chat_id=receiver_chat_id,bot_token=bot_token)
print(“msg sent on telegram”)

@Tradehull_Imran I have subscribed to dhan data API by paying 499+ tax
Still I am getting access denied in websocket.
Help me to resolve this.

1 Like

Sir, jo OTM liya hai uske hisab se Sl aur target kaise laga sakte hai? with Points?

@Tradehull_Imran Sir,

Now getting new error
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’

and i’m not finding any place order in code.

Regards,
Arun

Hi @rahulcse56

we need to give it receiver_chat_id and bot_token
see solution link : ChatGPT - New chat

1 Like

Hi @SOURAV_PROSAD

Webscoket is a old method we used to get ltp, now we have upgraded to a easier method.

do check solution link : Learn Algo Trading with Python | Codes | Youtube Series - #952 by Tradehull_Imran

Hi @babji3

use this code, for SL and TG based on options



import pdb
import time
import datetime
import traceback
from Dhan_Tradehull_V2 import Tradehull
import pandas as pd
from pprint import pprint
import talib
import pandas_ta as pta
import pandas_ta as ta
import warnings

warnings.filterwarnings("ignore")



# ---------------for dhan login ----------------
client_code = "1102790337"
token_id    = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJkaGFuIiwicGFydG5lcklkIjoiIiwiZXhwIjoxNzMyOTQzNzg5LCJ0b2tlbkNvbnN1bWVyVHlwZSI6IlNFTEYiLCJ3ZWJob29rVXJsIjoiIiwiZGhhbkNsaWVudElkIjoiMTEwMjc5MDMzNyJ9.hk6DAzd9YWb06hgFX9u7_Omq0srX2ofsgOp1qf2V7DIMT5OfVGN2IJds3MumsMh3wVon--TJSB9dmm5P6T3KWQ"


tsl = Tradehull(client_code,token_id)

traded = "no"
trade_info = {"options_name":None, "qty":None, "sl":None, "CE_PE":None}
reward_risk_ratio = 3


while True:

	current_time = datetime.datetime.now()

	index_chart  = tsl.get_historical_data(tradingsymbol='NIFTY DEC FUT', exchange='NFO', timeframe="5")
	time.sleep(5)
	index_ltp    = tsl.get_ltp_data(names = ['NIFTY DEC FUT'])['NIFTY DEC FUT']

	if (index_chart.empty):
		time.sleep(60)
		continue


	# rsi    ------------------------ apply indicators
	index_chart['rsi'] = talib.RSI(index_chart['close'], timeperiod=14)

	# vwap
	index_chart.set_index(pd.DatetimeIndex(index_chart['timestamp']), inplace=True)
	index_chart['vwap'] = pta.vwap(index_chart['high'] , index_chart['low'], index_chart['close'] , index_chart['volume'])

	# Supertrend
	indi = ta.supertrend(index_chart['high'], index_chart['low'], index_chart['close'], 10, 2)
	index_chart = pd.concat([index_chart, indi], axis=1, join='inner')


	# vwma
	index_chart['pv'] = index_chart['close'] * index_chart['volume']
	index_chart['vwma'] = index_chart['pv'].rolling(20).mean() / index_chart['volume'].rolling(20).mean()

	# volume
	volume = 50000

	first_candle   = index_chart.iloc[-3]
	second_candle  = index_chart.iloc[-2]
	running_candle = index_chart.iloc[-1]


	# ---------------------------- BUY ENTRY CONDITIONS ----------------------------
	bc1 = first_candle['close'] > first_candle['vwap']                # First Candle close is above VWAP
	bc2 = first_candle['close'] > first_candle['SUPERT_10_2.0']       # First Candle close is above Supertrend 
	bc3 = first_candle['close'] > first_candle['vwma']                # First Candle close is above VWMA
	bc4 = first_candle['rsi'] < 80                                    # First candle RSI < 80	
	bc5 = second_candle['volume'] > 50000                             # Second candle Volume should be greater than 50,000 for Nifty and above 125,000 for Bank Nifty
	bc6 = traded == "no"
	bc7 = index_ltp > first_candle['low']
	print(f"BUY \t {current_time} \t {bc1} \t {bc2} \t {bc3} \t {bc4} \t {bc5} \t {bc6} \t {bc7} \t first_candle {str(first_candle['timestamp'].time())}")


	# ---------------------------- SELL ENTRY CONDITIONS ----------------------------
	sc1 = first_candle['close'] < first_candle['vwap']                # First Candle close is below VWAP
	sc2 = first_candle['close'] < first_candle['SUPERT_10_2.0']       # First Candle close is below Supertrend 
	sc3 = first_candle['close'] < first_candle['vwma']                # First Candle close is below VWMA
	sc4 = first_candle['rsi'] > 20                                    # First candle RSI < 80	
	sc5 = second_candle['volume'] > 50000                             # Second candle Volume should be greater than 50,000 for Nifty and above 125,000 for Bank Nifty
	sc6 = traded == "no"
	sc7 = index_ltp < first_candle['high']
	print(f"SELL \t {current_time} \t {sc1} \t {sc2} \t {sc3} \t {sc4} \t {sc5} \t {sc6} \t {sc7} \t first_candle {str(first_candle['timestamp'].time())} \n")



	if bc1 and bc2 and bc3 and bc4 and bc5 and bc6 and bc7:
		print("Buy Signal Formed")

		ce_name, pe_name, ce_strike, pe_strike = tsl.OTM_Strike_Selection('NIFTY','05-12-2024',4)
		ce_ltp                     = tsl.get_ltp_data(names = [ce_name])[ce_name]
		lot_size                   = tsl.get_lot_size(ce_name)*1
		entry_orderid              = tsl.order_placement(ce_name,'NFO', lot_size, 0, 0, 'MARKET', 'BUY', 'MIS')
		traded                     = "yes"
		trade_info['options_name'] = ce_name
		trade_info['qty']          = lot_size
		sl_points                  = 20
		trade_info['sl']           = ce_ltp - sl_points
		trade_info['target']       = ce_ltp + reward_risk_ratio*sl_points
		trade_info['CE_PE']        = "CE"



	if sc1 and sc2 and sc3 and sc4 and sc5 and sc6 and sc7:
		print("Sell Signal Formed")

		ce_name, pe_name, ce_strike, pe_strike = tsl.OTM_Strike_Selection('NIFTY','05-12-2024',4)
		pe_ltp                     = tsl.get_ltp_data(names = [pe_name])[pe_name]
		lot_size                   = tsl.get_lot_size(pe_name)*1
		entry_orderid              = tsl.order_placement(pe_name,'NFO', lot_size, 0, 0, 'MARKET', 'BUY', 'MIS')
		traded                     = "yes"
		trade_info['options_name'] = pe_name
		trade_info['qty']          = lot_size
		sl_points                  = 20
		trade_info['sl']           = pe_ltp + sl_points
		trade_info['target']       = pe_ltp - reward_risk_ratio*sl_points	
		trade_info['CE_PE']        = "PE"



	# ---------------------------- check for exit SL/TG

	if traded == "yes":

		long_position  = trade_info['CE_PE'] == "CE"
		short_position = trade_info['CE_PE'] == "PE"


		if long_position:
			options_ltp     = tsl.get_ltp_data(names = [trade_info['options_name']])[trade_info['options_name']]
			sl_hit          = options_ltp < trade_info['sl']
			trailing_tg_hit = index_ltp < running_candle['SUPERT_10_2.0']   # this is a trailing target, by supertrend
			tg_hit          = options_ltp > trade_info['target']

			if sl_hit or trailing_tg_hit or tg_hit:
				print("Order Exited", trade_info)
				exit_orderid        = tsl.order_placement(trade_info['options_name'],'NFO', trade_info['qty'], 0, 0, 'MARKET', 'SELL', 'MIS')
				pdb.set_trace()





		if short_position:
			sl_hit          = index_ltp > trade_info['sl']
			trailing_tg_hit = index_ltp > running_candle['SUPERT_10_2.0']   # this is a trailing target, by supertrend
			tg_hit          = index_ltp < trade_info['target']

			if sl_hit or trailing_tg_hit or tg_hit:
				print("Order Exited", trade_info)
				exit_orderid        = tsl.order_placement(trade_info['options_name'],'NFO', trade_info['qty'], 0, 0, 'MARKET', 'SELL', 'MIS')
				pdb.set_trace()
















# trade_info = {
# 				'CE_PE': 'PE',
# 				'options_name': 'NIFTY 21 DEC 23350 PUT',
# 				'qty': 25,
# 				'sl': 23357.95
# 			}
1 Like

Hi @Arun_Rawat

Do send code, and complete error as well

Hi @Everyone

I am thinking on a joint project. Open Source Backtesting.

We will backtest and optimize strategy together and everyone will have access to final ruleset , Code files, and results generated,

Vote Here…

5 Likes