Learn Algo Trading with Python | Codes | Youtube Series

Thank you, @Tradehull_Imran. I will do it & let you know.

1 Like

@Tradehull_Imran
Got the instrument file
Pre market scanning ACC
Exception in Getting OHLC data as {‘status’: ‘failure’, ‘remarks’: {‘error_code’: ‘RS-9005’, ‘message’: ‘JSON parse error: Cannot deserialize value of type int from String “2024-01-21”: not a valid int value; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type int from String “2024-01-21”: not a valid int value\n at [Source: (PushbackInputStream); line: 1, column: 83] (through reference chain: co.dhan.api.model.HistoricalChartsRequest[“expiryCode”])’}, ‘data’: ‘’}
None

Very Good morning sir.
Can you please guide me, on how to import / install ‘alpvantage’ library. I have encountered with this in ‘Build My Algo’ file of Mumbai Work shop sir.
Thank you

import csv
import pdb
import os
import time
import math
import requests
import datetime
import pandas as pd
from datetime import datetime
from openpyxl import load_workbook
from Dhan_Tradehull_V2 import Tradehull
import logging
from ratelimit import limits, sleep_and_retry

Client details

client_code = “"
token_id = "
******************************”
tsl = Tradehull(client_code, token_id)

Watchlist and parameters

indx = [‘NIFTY’] #Variable
nifty_expiry = “NIFTY 23 JAN” #Variable
strike_interval = 50 #Variable

File path

excel_file = “Nifty.xlsx”

Function to append OHLC data to Excel file

def append_nifty_to_excel(file, data, sheet_name):
df_nifty = pd.DataFrame([data])
if not os.path.exists(file):
df_nifty.to_excel(file, index=False, sheet_name=sheet_name)
else:
book_nifty = load_workbook(file)
with pd.ExcelWriter(file, mode=“a”, engine=“openpyxl”, if_sheet_exists=“overlay”) as writer:
df_nifty.to_excel(writer, index=False, sheet_name=sheet_name, startrow=book_nifty[sheet_name].max_row, header=False)

Rounding function

def mround(value, multiple):
if multiple == 0:
return 0
return round(value / multiple) * multiple

Market open/close times

market_start_time = datetime.strptime(“09:15:00.0”, “%H:%M:%S.%f”).time()
market_end_time = datetime.strptime(“15:31:00.0”, “%H:%M:%S.%f”).time()

nifty_high =
nifty_low =
Final_high =
FInal_low =

while True:
time_now = datetime.now().time()

if time_now < market_start_time:
    print(f"Wait for market to start, current time: {time_now}")
    time.sleep(1)

elif time_now > market_end_time:
    print(f"Market is over, See you tomorrow, current time: {time_now}")
    break

else:
    log(f"Market is open, current time: {time_now}")
    
    while True:
        # Wait until the start of the next minute
        now = datetime.now()
        sleep_time = 60 - now.second - now.microsecond / 1_000_000  # Sleep until next minute
        time.sleep(sleep_time)  # Sync with the next minute start

        # Start time of execution
        start_time = datetime.now()
        print(f"Running at: {start_time.strftime('%H:%M:%S')}")

        # Get Nifty intraday data
        nifty_chart = tsl.get_intraday_data('NIFTY', 'INDEX', 1)

        if not nifty_chart.empty:
            nifty_chart['timestamp'] = pd.to_datetime(nifty_chart['timestamp'])
            nifty_lc_data = nifty_chart.iloc[0:-2]

            # Use parentheses to call the methods
            nifty_last_high = nifty_lc_data['high'].max()  
            nifty_last_low = nifty_lc_data['low'].min()     
            
            nifty_lc_low = nifty_lc_data.iloc[-1]['low']
            nifty_lc_high = nifty_lc_data.iloc[-1]['high']
            nifty_lc_open = nifty_lc_data.iloc[-1]['open']
            nifty_lc_close = nifty_lc_data.iloc[-1]['close']
            ts_nifty_chart = nifty_lc_data.iloc[-1]['timestamp']
            
            if not nifty_high or nifty_last_high > max(nifty_high):
                nifty_high.append(nifty_last_high)
            if not nifty_low or nifty_last_low < min(nifty_high):
                nifty_low.append(nifty_last_low)
            
            nifty_high_ret = max(nifty_high)
            nifty_low_ret = min(nifty_low)
            
            nifty_rectracement_high = nifty_high_ret - (nifty_high_ret - nifty_low_ret) * 0.236
            nifty_rectracement_low = nifty_low_ret + (nifty_high_ret - nifty_low_ret) * 0.236

            # Initialize final values
            nifty_final_high = None
            nifty_final_low = None

            # Flag for crossing below nifty_rectracement_high
            if nifty_lc_low < nifty_rectracement_high:
                nifty_rectrace_high = True
                if nifty_rectrace_high and nifty_last_high > max(nifty_high):
                    nifty_final_high = nifty_last_high
                else:
                    nifty_final_high = nifty_high_ret
            else:
                nifty_final_high = nifty_high_ret

            # Flag for crossing above nifty_rectracement_low
            if nifty_lc_high > nifty_rectracement_low:
                nifty_rectrace_low = True
                if nifty_rectrace_low and nifty_last_low < min(nifty_low):
                    nifty_final_low = nifty_last_low
                else:
                    nifty_final_low = nifty_low_ret
            else:
                nifty_final_low = nifty_low_ret

            # Strike price calculations
            if nifty_final_high is not None:
                nifty_strike_ce = mround(nifty_final_high, strike_interval) - (strike_interval * 2)
                nifty_ce_strike_symbol = f"{nifty_expiry} {nifty_strike_ce} CALL"
                print(f"CALL Strike Symbol: {nifty_ce_strike_symbol}")

            if nifty_final_low is not None:
                nifty_strike_pe = mround(nifty_final_low, strike_interval) + (strike_interval * 2)
                nifty_pe_strike_symbol = f"{nifty_expiry} {nifty_strike_pe} PUT"
                print(f"PUT Strike Symbol: {nifty_pe_strike_symbol}")

        # else:
        #     print("No data received for NIFTY intraday.")
            ts_nifty_chart = nifty_lc_data.iloc[-1]['timestamp'].tz_localize(None)
            # Prepare data for Excel
            nifty_ohlc_data = {
                "Symbol": "NIFTY",
                "Datetime": ts_nifty_chart,
                "Open": nifty_lc_open,
                "High": nifty_lc_high,
                "Low": nifty_lc_low,
                "Close": nifty_lc_close,
                "Last_High": nifty_last_high,
                "Last_low": nifty_last_low,
                "Retracement_High": nifty_rectracement_high,
                "Retracement_Low": nifty_rectracement_low,
                "Final_High": nifty_final_high,
                "Final_Low": nifty_final_low,
                "Call_Strike": nifty_ce_strike_symbol,
                "Put_Strike": nifty_pe_strike_symbol,
            }

            # Append data to Excel
            append_nifty_to_excel(excel_file, nifty_ohlc_data, "nifty_index")

Hi @Spasarkar04 ,

Can you share your whole code?

Hi @Kanha_Meher ,

The code seems to be correct, make sure the internet connection is stable.

Hi @Vasili_Prasad ,

You can install and import the the alpvatange library by using the pip command as below:

pip install alpha-vantage
import alpha-vantage
1 Like

Hi, @Tradehull_Imran I’m having an issue. the code you have given me for super trend its working good, but there is a problem

problem-1 supertrend niche hoga tobhi buy order place kar rha hai aur supertrend jiska already cross hokr 1-2 din hogya use pr order place karrha rha.

what should I do here…

mujhe sirf jb supertrend cross kre tabhi buy hona chahiye uske niche ya already cross hogya tb nhi.

code -


import time
import datetime
import pandas as pd
import pandas_ta as ta
from Dhan_Tradehull_V2 import Tradehull
import warnings

warnings.filterwarnings("ignore")

# ---------------for dhan login ----------------
client_code = "1111111111"
token_id = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJkaGFuIiwicGFydG5lcklkIjoiIiwiZXhwIjoxNzM5MjY5OTEyLCJ0b2tlbkNvbnN1bWVyVHlwZSI6IlNFTEYiLCJ3ZWJob29rVXJsIjoiIiwiZGhhbkNsaWVudElkIjoiMTEwMjk1NTI5MCJ9.5aG1-NOtFA3Bhsta9LZAdFsvljkz7sI_mXMDJ82QtumR67DLvUrFyJM8zUN3QO9_VpXaJK-leRqmMQIfxN6qCA"

# Initialize Tradehull API
tsl = Tradehull(client_code, token_id)

# List of stocks to monitor
stocks = ["MARICO", "ENDURANCE", "IPCALAB", "POLYMED", "FINPIPE", "MOTHERSON", "LUPIN", "VIJAYA", "ZYDUSLIFE", "GILLETTE"]

# Variables to track trades for each stock
trade_info = {stock: {"traded": "no", "qty": None, "entry_price": None} for stock in stocks}

while True:
    current_time = datetime.datetime.now()

    for stock in stocks:
        # Fetch 1-hour historical data
        stock_chart = tsl.get_historical_data(tradingsymbol=stock, exchange='NSE', timeframe="1")
        time.sleep(3)
        stock_ltp = tsl.get_ltp_data(names=[stock])[stock]

        if stock_chart is None:
            time.sleep(60)
            continue

        # Apply Supertrend indicator
        supertrend = ta.supertrend(stock_chart['high'], stock_chart['low'], stock_chart['close'], 10, 3)
        stock_chart = pd.concat([stock_chart, supertrend], axis=1, join='inner')

        # Get the latest two candles
        first_candle = stock_chart.iloc[-2]
        running_candle = stock_chart.iloc[-1]

        # ---------------------------- BUY ENTRY CONDITION ----------------------------
        buy_condition = (
            first_candle['SUPERT_10_3.0'] < first_candle['close'] and  # Supertrend is green
            trade_info[stock]['traded'] == "no"
        )

        # ---------------------------- EXIT CONDITION ----------------------------
        exit_condition = (
            running_candle['SUPERT_10_3.0'] > running_candle['close'] and  # Supertrend turns red
            trade_info[stock]['traded'] == "yes"
        )

        if buy_condition:
            print(f"{current_time}: Buy Signal Detected for {stock}")

            qty = 1  # Example: fixed quantity to buy
            entry_orderid = tsl.order_placement(stock, 'NSE', qty, 0, 0, 'MARKET', 'BUY', 'CNC')

            trade_info[stock]['traded'] = "yes"
            trade_info[stock]['qty'] = qty
            trade_info[stock]['entry_price'] = tsl.get_executed_price(orderid=entry_orderid)

        if exit_condition:
            print(f"{current_time}: Exit Signal Detected for {stock}")

            exit_orderid = tsl.order_placement(
                stock, 'NSE', trade_info[stock]['qty'], 0, 0, 'MARKET', 'SELL', 'CNC')

            trade_info[stock] = {"traded": "no", "qty": None, "entry_price": None}

    time.sleep(3600)  # Run every hour for swing trading


out put-


C:\Dhan\8. Session8- 2nd Live Algo\8. Session 8 Dhan_Tradehull_V2>py 1.py
Codebase Version 2.4 : Solved - Option Chain
-----Logged into Dhan-----
reading existing file all_instrument 2025-01-21.csv
Got the instrument file
2025-01-21 15:01:44.024087: Buy Signal Detected for MARICO
2025-01-21 15:01:44.024087: Buy Signal Detected for ENDURANCE
2025-01-21 15:01:44.024087: Buy Signal Detected for POLYMED
2025-01-21 15:01:44.024087: Buy Signal Detected for FINPIPE
2025-01-21 15:01:44.024087: Buy Signal Detected for MOTHERSON
2025-01-21 15:01:44.024087: Buy Signal Detected for VIJAYA
2025-01-21 15:01:44.024087: Buy Signal Detected for GILLETTE

Thank You sir, I could successfully, install using the first line ‘pip install alpha-vantage’

And I have changed the existing library name from ‘import alpvantage’ with ‘import alpha-vantage’
as per your guide lines.

But still getting error as ‘invalid syntax’ pointing out the hyphon used in alpha-vantage. How to resolve this sir?

Hi @Vasili_Prasad
check this library for easy access : alpha-vantage · PyPI

I,m getting this issue in premarket scanner

-----Logged into Dhan-----
This BOT Is Picking New File From Dhan
Got the instrument file
Pre market scanning INFY
Exception in Getting OHLC data as {‘status’: ‘failure’, ‘remarks’: {‘error_code’: ‘RS-9005’, ‘message’: ‘JSON parse error: Cannot deserialize value of type int from String “2024-01-22”: not a valid int value; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type int from String “2024-01-22”: not a valid int value\n at [Source: (PushbackInputStream); line: 1, column: 85] (through reference chain: co.dhan.api.model.HistoricalChartsRequest[“expiryCode”])’}, ‘data’: ‘’}
Traceback (most recent call last):
File “/Users/shreyasavinashpasarkar/Desktop/Shreenu/Shreyas Algo/Pre Market Scanner.py”, line 29, in
ldc = daily_data.iloc[-1] #last_day_candle
^^^^^^^^^^^^^^^
AttributeError: ‘NoneType’ object has no attribute ‘iloc’

@Tradehull_Imran

1 hour historical data only giving 13 rows and hence all indicator reading are failing. Supertrend give positive when its negative. check for pageind.

as per dhan , we should get last 5 days data. can you please check urgently why we only getting last 2 days.

run below for pageind and see how wrong is data
chart = tsl.get_historical_data(tradingsymbol = stocks,exchange = ‘NSE’,timeframe=“60”)

        ST = round(ta.supertrend(chart['high'], chart['low'], chart['close'], 10, 3), 2)
        ST1 = pd.concat([chart, ST], axis=1, join='inner')

if you see data start from monday , which is wrong. it should give data for last 5 trading days. what kind of issue is this @Dhan @Hardik

Very Good Morning Sir, I was trying to use the ‘Breakout Algo’ of Session-9
I am getting the error sir.

# 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 = ['APOLLOHOSP']
traded_wathclist = []
tarde_info = {'Direction': 'buy', 'level': 7014.95}


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,'30-01-2025')  #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)
And the Error in command Prompt:
C:\Users\LENOVO PC\Desktop\RP\DHAN Algorhythemic Trading\9. Session9- 3rd Live Algo Version 2\3rd live Algo>py "Breakout Algo on Stock Options.py"
Codebase Version 2.3 : Solved - ATM issues
-----Logged into Dhan-----
reading existing file all_instrument 2025-01-22.csv
Got the instrument file
Scaning APOLLOHOSP
exception got in ce_pe_option_df '<' not supported between instances of 'int' and 'str'
Exception for instrument name None as 'NoneType' object has no attribute 'upper'
Enter valid Script Name
Traceback (most recent call last):
  File "Breakout Algo on Stock Options.py", line 67, in <module>
    entry_price    = round((atm_ce_ltp*1.02),1)
TypeError: unsupported operand type(s) for *: 'dict' and 'float'


@Tradehull_Imran

Hi @Spasarkar04 ,

Do refer the below video to fetch the historical data:

Hi @Spasarkar04 ,

Currently dhan api is not supporting for 10 min timeframe, use any of other supported timeframe’s.

Hi @Vasili_Prasad ,

Use ATM selection function as below :

atm_ce_name, atm_pe_name, strike = tsl.ATM_Strike_Selection(stock_name, 0)

0 - for current expiry
1 - for next expiry, and so on

To get the ltp from the dictionary use code as below:

atm_ce_ltp     = tsl.get_ltp_data(names = [atm_ce_name])
atm_ce_ltp     = atm_ce_ltp[atm_ce_name]

Hi @virender_singh ,

To get the last 5 days data from dhan api, make the changes in Dhan_Tradehull_V2 file get_start_date() function.

start_date = df.iloc[-2]['timestamp'] # change -2 to -5
1 Like

Hi @Sameer_Shaikh ,

Do refer the below code.


# List of stocks to monitor
stocks = ["MARICO", "ENDURANCE", "IPCALAB", "POLYMED", "FINPIPE", "MOTHERSON", "LUPIN", "VIJAYA", "ZYDUSLIFE", "GILLETTE"]

# Variables to track trades for each stock
trade_info = {stock: {"traded": "no", "qty": None, "entry_price": None} for stock in stocks}

while True:
	current_time = datetime.datetime.now()

	for stock in stocks:
		# Fetch 1-hour historical data
		stock_chart = tsl.get_historical_data(tradingsymbol=stock, exchange='NSE', timeframe="1")
		time.sleep(3)
		stock_ltp = tsl.get_ltp_data(names=[stock])[stock]

		if stock_chart is None:
			time.sleep(60)
			continue

		# Apply Supertrend indicator
		supertrend = ta.supertrend(stock_chart['high'], stock_chart['low'], stock_chart['close'], 10, 3)
		stock_chart = pd.concat([stock_chart, supertrend], axis=1, join='inner')

		# Get the latest two candles
		previous_completed_candle = stock_chart.iloc[-3]
		completed_candle = stock_chart.iloc[-2]
		running_candle = stock_chart.iloc[-1]
		buy_condition1 =(previous_completed_candle['SUPERTd_10_3.0'] == -1) and (completed_candle['SUPERTd_10_3.0'] == 1)
		buy_condition2 = trade_info[stock]['traded'] == "no" 

		# ---------------------------- EXIT CONDITION ----------------------------
		exit_condition = (running_candle['SUPERT_10_3.0'] > running_candle['close']) and (trade_info[stock]['traded'] == "yes")

		if buy_condition1 and buy_condition2:
			print(f"{current_time}: Buy Signal Detected for {stock}")

			qty = 1  # Example: fixed quantity to buy
			entry_orderid = tsl.order_placement(stock, 'NSE', qty, 0, 0, 'MARKET', 'BUY', 'CNC')

			trade_info[stock]['traded'] = "yes"
			trade_info[stock]['qty'] = qty
			trade_info[stock]['entry_price'] = tsl.get_executed_price(orderid=entry_orderid)

		if exit_condition:
			print(f"{current_time}: Exit Signal Detected for {stock}")

			exit_orderid = tsl.order_placement(
				stock, 'NSE', trade_info[stock]['qty'], 0, 0, 'MARKET', 'SELL', 'CNC')

			trade_info[stock] = {"traded": "no", "qty": None, "entry_price": None}

	time.sleep(3600) 

Let me know if the code works.