Learn Algo Trading with Python | Codes | Youtube Series

sir @Tradehull_Imran

Thank you very much for your very quick response sir.

VBR Prasad

1 Like

Hi @Subhajitpanja

use this file : Dhan_Tradehull_V2.py - Google Drive

also for TATAMOTORS use expiry as 26-12-2024

sir vwma ka value nhi aa rha hai…

Hi @Subhajitpanja
Also for instrument file issue, update the login code to

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

client_code = ""
token_id    = ""

tsl = Tradehull(client_code,token_id)
print(os.listdir("Dependencies"))

and send the output

Hi @vinay_kumaar
Send complete code you are using

@Tradehull_Imran sir now it is working fine.
but just informing
all_instrument 2024-12-09.csv
file is not there
old one I deleted no new one generated.(although it is not required)

Output:
Codebase Version 2.3 : Solved - ATM issues
-----Logged into Dhan-----
reading existing file all_instrument 2024-12-09.csv
Got the instrument file
[‘all_instrument 2024-12-09.csv’, ‘log_files’]

@Tradehull_Imran sir

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 ----------------

tsl = Tradehull(client_code,token_id)

traded = “no”
trade_info = {“options_name”:None, “qty”:None, “sl”:None, “CE_PE”:None}

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):
# 	print("market is close",current_time)
# 	break

print("Algo Bot is working",current_time)	

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


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


# Conditions that are on 1 minute timeframe
# 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')

# mom
index_chart['mom'] =talib.MOM(index_chart['close'], timeperiod=10)

# Conditions that are on 5 minute timeframe
# rsi    ------------------------ apply indicators
index_chart_1['rsi'] = talib.RSI(index_chart_1['close'], timeperiod=14)

# mom
index_chart_1['mom'] =talib.MOM(index_chart_1['close'], timeperiod=10)

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

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


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


# Conditions that are on 15 minute timeframe
# rsi    ------------------------ apply indicators
index_chart_2['rsi'] = talib.RSI(index_chart_2['close'], timeperiod=14)
index_chart_2['pv'] = index_chart_2['rsi'] * index_chart_2['volume']
index_chart_2['rsivwma'] = index_chart_2['pv'].rolling(10).mean() / index_chart_2['volume'].rolling(10).mean()


# mom
index_chart_2['mom'] =talib.MOM(index_chart_2['close'], timeperiod=10)

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

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


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


# volume
volume = 50000

# Conditions that are on 1 minute timeframe
first_candle   = index_chart.iloc[-3]
second_candle  = index_chart.iloc[-2]
running_candle = index_chart.iloc[-1]

# Conditions that are on 5 minute timeframe
first_candle_1   = index_chart_1.iloc[-3]
second_candle_1  = index_chart_1.iloc[-2]
running_candle_1 = index_chart_1.iloc[-1]

# Conditions that are on 15 minute timeframe
first_candle_2   = index_chart_2.iloc[-3]
second_candle_2  = index_chart_2.iloc[-2]
running_candle_2 = index_chart_2.iloc[-1]
pdb.set_trace()

# ---------------------------- BUY ENTRY CONDITIONS 1 MINUTE TIMEFRAME ----------------------------
bc1  = first_candle['close']      > first_candle['SUPERT_10_2.0']        # first_candle close is above Supertrend 
bc2  = second_candle['mom']       > 25                                   # first_candle MOM > 25                                  

# ---------------------------- BUY ENTRY CONDITIONS 5 MINUTE TIMEFRAME ----------------------------
bc3  = first_candle_1['close']   > first_candle_1['vwap']                # first_candle_1 close is above VWAP         
bc4  = first_candle_1['close']   > first_candle_1['SUPERT_10_2.0']       # first_candle_1 close is above Supertrend 
bc5  = first_candle_1['close']   > first_candle_1['vwma']                # first_candle_1 close is above VWMA	
bc6  = first_candle_1['mom']     > 25	                                 # first_candle_1 MOM > 25
bc7  = first_candle_1['rsi']     < 80                                    # first_candle_1 RSI < 80	
bc8  = second_candle_1['volume'] > 50000                                 # second_candle_1 Volume should be greater than 50,000 for Nifty and above 125,000 for Bank Nifty
bc9  = traded == "no"
bc10 = index_ltp > first_candle_1['low']

# ---------------------------- BUY ENTRY CONDITIONS 15 MINUTE TIMEFRAME ----------------------------
bc11 = first_candle_2['close']   > first_candle_2['vwap']                # first_candle_2 close is above VWAP
bc12 = first_candle_2['close']   > first_candle_2['SUPERT_10_2.0']       # first_candle_2 close is above Supertrend 
bc13 = first_candle_2['close']   > first_candle_2['vwma']                # first_candle_2 close is above VWMA
bc14 = first_candle_2['rsi']     > index_chart_2['rsivwma']              # first_candle_2 rsi is above rsivwma (timeperiod=100)                    	
bc15 = first_candle_2['mom']     > 25                                    # first_candle_2 MOM > 25
bc16 = first_candle_2['rsi']     > 50                                    # first_candle_2 RSI > 50	
bc17 = traded == "no"
bc18 = index_ltp > first_candle_2['low']
print(f"BUY \t {current_time} \t {bc1} \t {bc2} \t {bc3} \t {bc4} \t {bc5} \t {bc6} \t {bc7} \t {bc8} \t {bc9} \t {bc10} \t {bc11} \t {bc12} \t {bc13} \t {bc14} \t {bc15} \t {bc16} \t {bc17} \t {bc18} \t first_candle_1 {str(first_candle_1['timestamp'].time())} \n")


# ---------------------------- SELL ENTRY CONDITIONS 1 MINUTE TIMEFRAME ----------------------------
sc1  = first_candle['close']      < first_candle['SUPERT_10_2.0']        # first_candle close is below Supertrend 
sc2  = second_candle['mom']       < -25                                  # first_candle MOM > -25


# ---------------------------- SELL ENTRY CONDITIONS 5 MINUTE TIMEFRAME ----------------------------
sc3 = first_candle_1['close']    < first_candle_1['vwap']                # first_candle_1 close is below VWAP
sc4  = first_candle_1['close']   < first_candle_1['SUPERT_10_2.0']       # first_candle_1 close is below Supertrend 
sc5= first_candle_1['close']     < first_candle_1['vwma']                # first_candle_1 close is below VWMA
sc6  = first_candle_2['mom']     < -25                                   # first_candle_1 MOM < -25
sc7  = first_candle_1['rsi']     < 80                                    # first_candle_1 RSI < 80	
sc8  = second_candle_2['volume'] > 50000                                 # Second candle Volume should be greater than 50,000 for Nifty and above 125,000 for Bank Nifty
sc9  = traded == "no"
sc10 = index_ltp < first_candle_1['high']


# ---------------------------- SELL ENTRY CONDITIONS 15 MINUTE TIMEFRAME----------------------------
sc11 = first_candle_2['close']   < first_candle_2['vwap']                # first_candle_2 close is below VWAP
sc12 = first_candle_2['close']   < first_candle_2['SUPERT_10_2.0']       # first_candle_2 close is below Supertrend 
sc13 = first_candle_2['close']   < first_candle_2['vwma']                # first_candle_2 close is below VWMA
bc14 = first_candle_2['rsi']     < index_chart_2['rsivwma']              # first_candle_2 rsi is below rsivwma  (timeperiod=100)                   		
sc15 = first_candle_2['mom']     < -25                                   # first_candle_2 MOM < -25
sc16 = first_candle_2['rsi']     < 50                                    # first_candle_2 RSI < 50	
sc17 = traded == "no"
sc18 = index_ltp < first_candle_2['high']
print(f"SELL \t {current_time} \t {sc1} \t {sc2} \t {sc3} \t {sc4} \t {sc5} \t {sc6} \t {sc7} \t {sc8} \t {sc9} \t {sc10} \t {sc11} \t {sc12} \t {sc13} \t {sc14} \t {sc15} \t {sc16} \t {bc17} \t {bc18} \t first_candle_1 {str(first_candle_1['timestamp'].time())} \n")  


if bc1 and bc2 and bc3 and bc4 and bc5 and bc6 and bc7 and bc8 and bc9 and bc10 and bc11 and bc12 and bc13 and bc14 and bc15 and bc16 and bc17 and bc18:
	print("Buy Signal Formed Order Is Fired")
    
	ce_name, pe_name, strike      = tsl.ATM_Strike_Selection(Underlying ='NIFTY',Expiry ='12-12-2024')
	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
	trade_info['sl']              = first_candle_1['low']
	trade_info['CE_PE']           = "CE"
	trade_info['tg_hit']          = tg_hit
	exit_processed                = False    
	
   	    
if sc1 and sc2 and sc3 and sc4 and sc5 and sc6 and sc7 and sc8 and sc9 and sc10 and sc11 and sc12 and sc13 and sc14 and sc15 and sc16 and sc17 and sc18:
	print("Sell Signal Formed Order Is Fired")

	ce_name, pe_name, strike      = tsl.ATM_Strike_Selection(Underlying ='NIFTY',Expiry ='12-12-2024')
	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
	trade_info['sl']              = first_candle_1['high']
	trade_info['CE_PE']           = "PE"
	trade_info['tg_hit']          = tg_hit
	exit_processed                = False       

# ---------------------------- 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']
		tg_hit = index_ltp < running_candle_1['SUPERT_10_2.0']

		if sl_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')
			traded = "no"
			

	if short_position:
		sl_hit = index_ltp > trade_info['sl']
		tg_hit = index_ltp > running_candle_1['SUPERT_10_2.0']

		if sl_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')
			traded = "no"

order_details = tsl.cancel_all_orders()

pdb.set_trace()

sir check this line
bc14 = first_candle_2[‘rsi’] > index_chart_2[‘rsivwma’] # first_candle_2 rsi is above rsivwma (timeperiod=100)

condition false hai par true dikha rha hai …

sir
is code me daily pivot or weekly pivot add karna chahta hu…

Hi @vinay_kumaar

I am using this code,

	index_chart_2 = tsl.get_historical_data(tradingsymbol='NIFTY DEC FUT', exchange='NFO', timeframe="15")
	index_chart_2['rsi'] = talib.RSI(index_chart_2['close'], timeperiod=14)
	index_chart_2['pv'] = index_chart_2['rsi'] * index_chart_2['volume']
	index_chart_2['rsivwma'] = index_chart_2['pv'].rolling(10).mean() / index_chart_2['volume'].rolling(10).mean()

this shows correct values for rsivwma

Also, do apply this indicator on NIFTY DEC FUT, in tradingview it has been applied on nifty

Hi @vinay_kumaar

use below pseudocode


def get_pivot_point(chart):
    chart = chart.iloc[-1]
    PP = (chart['high'].max() + chart['low'].min() + chart["close"].iloc[-1])/3 
    R1 = 2 * PP - chart['low'].min()
    R2 = PP + (chart['high'].max() - chart['low'].min())         
    R3 = PP + 2 * (chart['high'].max() - chart['low'].min())          
    S1 = 2 * PP - chart['high'].max()          
    S2 = PP - (chart['high'].max() - chart['low'].min())
    S3 = PP - 2 * (chart['high'].max() - chart['low'].min()) 

Hi @Subhajitpanja
all_instrument 2024-12-09.csv is present in Dependencies folder, but somehow on vscode it does not shows up,

now since all_instrument 2024-12-09.csv is present , the lots sizes, and step values that the codebase reads are correct, so no issue. we can safely ignore the vscode issue.

day or weekly ke liye iloc[ ?]

The issue still persist

Exception in Getting OHLC data as {‘status’: ‘failure’, ‘remarks’: {‘error_code’: ‘DH-904’, ‘error_type’: ‘Rate_Limit’, ‘error_message’: ‘Too many requests on server from single user breaching rate limits. Try throttling API calls.’}, ‘data’: {‘errorType’: ‘Rate_Limit’, ‘errorCode’: ‘DH-904’, ‘errorMessage’: ‘Too many requests on server from single user breaching rate limits. Try throttling API calls.’}}

I have updated the Dhan_Tradehull_V2 as you have replied.
It had worked for sometime and after that issue re-started.

But I have checked in folder also by the windows explorer

I couldn’t find that file
I will try to send you screenshot also

But not occuring any problem :grinning:

We can ignore now.I think we will modify many things in next version

Dhan api also introducing Option chain very soon @Tradehull_Imran sir

Today am facing same issue, Data not fetching

previous day ka data nhi mil pa rha