Learn Algo Trading with Python | Codes | Youtube Series

Hello @Zee2Zahid

I think you should request LTP data in every 2.25 sec.

because per day Data request max limit is 10000, and we have 375 min in one trading session. so you can make 26.66666667 data requests every min, hence 1 data request in 2.25 min will be safest for you.

Hope this will help you… and let me know, if i am wrong. @Tradehull_Imran

1 Like

Hi
@Tradehull_Imran

I am trying to get supertrend data
But there is something going wrong
I have applied code as you posted

import pandas_ta as ta

chart_15 [‘supertrend’] = ta.supertrend(chart_15[‘high’], chart_15[‘low’], chart_15[‘close’],7,3)


error shows

Traceback (most recent call last):
File “Supertrend Practice.py”, line 49, in
chart_15 [‘supertrend’] = ta.supertrend(chart_15[‘high’], chart_15[‘low’], chart_15[‘close’],7,3)
File “C:\Users\kalpe\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\frame.py”, line 3940, in setitem
self._set_item_frame_value(key, value)
File “C:\Users\kalpe\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\frame.py”, line 4094, in _set_item_frame_value
raise ValueError(
ValueError: Cannot set a DataFrame with multiple columns to the single column supertrend


Please verify
Thank You

Hi @Kalpeshh_Patel ,
Although @Tradehull_Imran Sir give you the final solution
But I got some solutions
can you try these if possible

Solution 1

The error you’re encountering is because the ta.supertrend function returns a DataFrame with multiple columns, and you’re trying to assign it to a single column in your DataFrame. To fix this, you need to assign the multiple columns returned by ta.supertrend to separate columns in your DataFrame.

Here’s how you can modify your code:

import pandas_ta as ta

# Calculate the supertrend
supertrend = ta.supertrend(chart_15['high'], chart_15['low'], chart_15['close'], 7, 3)

# Assign the supertrend columns to your DataFrame
chart_15['supertrend'] = supertrend['SUPERT_7_3.0']
chart_15['supertrend_direction'] = supertrend['SUPERTd_7_3.0']
chart_15['supertrend_lower_band'] = supertrend['SUPERTl_7_3.0']
chart_15['supertrend_upper_band'] = supertrend['SUPERTs_7_3.0']

Explanation:

  • ta.supertrend: This function returns a DataFrame with multiple columns, including the supertrend value, direction, lower band, and upper band.
  • chart_15['supertrend']: Assigns the supertrend value to a new column in your DataFrame.
  • chart_15['supertrend_direction']: Assigns the supertrend direction to a new column in your DataFrame.
  • chart_15['supertrend_lower_band']: Assigns the supertrend lower band to a new column in your DataFrame.
  • chart_15['supertrend_upper_band']: Assigns the supertrend upper band to a new column in your DataFrame.

Solution 2

The error occurs because the ta.supertrend function returns a DataFrame with multiple columns (e.g., SUPERT_7_3, SUPERTd_7_3, etc.), but you’re trying to assign it to a single column chart_15['supertrend']. You need to assign each returned column to its respective column in your DataFrame or work with the entire returned DataFrame.

Here’s how you can fix it:

Option 1: Assign Each Column Explicitly

import pandas_ta as ta

# Calculate the supertrend
supertrend = ta.supertrend(chart_15['high'], chart_15['low'], chart_15['close'], length=7, multiplier=3)

# Add each column to the DataFrame
chart_15['supertrend'] = supertrend['SUPERT_7_3']
chart_15['supertrend_direction'] = supertrend['SUPERTd_7_3']

Option 2: Merge the Returned DataFrame

If you want to add all columns returned by ta.supertrend into chart_15 at once:

import pandas_ta as ta

# Calculate the supertrend and merge it with the original DataFrame
supertrend = ta.supertrend(chart_15['high'], chart_15['low'], chart_15['close'], length=7, multiplier=3)
chart_15 = chart_15.join(supertrend)

import pandas_ta as ta

Calculate the supertrend and merge it with the original DataFrame

supertrend = ta.supertrend(chart_15[‘high’], chart_15[‘low’], chart_15[‘close’], length=7, multiplier=3)
chart_15 = chart_15.join(supertrend)

Solution 3

Error Analysis:

The error message ValueError: Cannot set a DataFrame with multiple columns to the single column supertrend indicates that the ta.supertrend function in pandas_ta returns a DataFrame with multiple columns. However, you’re trying to assign it directly to a new column named 'supertrend' in your DataFrame chart_15. This mismatch in dimensionality is causing the error.

Solution:

Here’s a corrected version of your code that retrieves the desired Supertrend column and assigns it appropriately:

import pandas_ta as ta

# Assuming 'chart_15' is your DataFrame containing OHLC (Open, High, Low, Close) data

# Calculate the Supertrend indicator
supertrend_data = ta.supertrend(chart_15['high'], chart_15['low'], chart_15['close'], length=7, multiplier=3)

# Extract the desired column (usually the first one, which represents the Supertrend value)
supertrend_values = supertrend_data.iloc[:, 0]

# Add the Supertrend values as a new column to 'chart_15'
chart_15['Supertrend'] = supertrend_values

print(chart_15)  # This will now show 'chart_15' with the added 'Supertrend' column

Explanation:

  1. Import the pandas_ta library: This line remains the same as it’s necessary for using the supertrend function.
  2. Calculate the Supertrend indicator: We call ta.supertrend with the required OHLC data from chart_15 and your chosen parameters (length=7 and multiplier=3).
  3. Extract the desired column: The supertrend_data variable will be a DataFrame with multiple columns, typically named according to the function’s parameters. We extract the first column (iloc[:, 0]) because it usually contains the actual Supertrend values.
  4. Add the Supertrend column: We create a new column named 'Supertrend' in chart_15 and assign the extracted values to it.

Additional Considerations:

  • Column Naming: You can customize the new column name in step 4 (e.g., 'STrend', 'Super_Trend').
  • Supertrend DataFrame Columns: The exact column names in supertrend_data might vary slightly depending on the specific version of pandas_ta you’re using. Consult the library’s documentation for up-to-date information.

With these modifications, you should be able to successfully calculate and add the Supertrend data to your chart_15 DataFrame in pandas.

Solution 4

The error message you’re seeing indicates that the pandas_ta.supertrend function is returning a DataFrame with multiple columns, but you’re trying to assign it to a single column in your chart_15 DataFrame.

To fix this, you need to assign each column of the returned DataFrame to a separate column in your chart_15 DataFrame. You can do this by specifying the column names in the assignment statement.

Here’s an example of how you can modify your code:

chart_15[['supertrend_lower', 'supertrend_upper', 'supertrend_signal']] = ta.supertrend(chart_15['high'], chart_15['low'], chart_15['close'], 7, 3)

In this example, I’ve assumed that the pandas_ta.supertrend function returns three columns: supertrend_lower, supertrend_upper, and supertrend_signal. You may need to adjust the column names based on the actual output of the pandas_ta.supertrend function.

By assigning each column separately, you should be able to avoid the ValueError you’re experiencing.

1 Like

Hi Sir, I am still unable to get the LTP data and also getting other errors. I have already uploaded my folder in google drive and shared it with you. Please help me sir, thank you.

DEAR SIR
i have download the latest dhan tradehull as your given link, i git the historical data of nifty option,but at the same time using this trade hull ,i run the code for intraday data ,then ir showing the error ,but same code i run with previous tradehull ,intraday data running fine. how to solve it
i want to calculate ema 20 for option strike price,but i can get the data before 9.35am.
so i need 20 candle of previous day chart,so that i can get ema at 9.15 onward.

please reply me

Hi
It’s works
Thank You Shubh

1 Like

Hello Imran Sir / @Tradehull_Imran,

I am not able to get any LTP and historical data. I used below code for LTP.

Error I am getting below in log file:

Please help me on this. FYI. already subscribe the Data API.
Thanks in advance
Sudip Nath

hi sir @Tradehull_Imran
my algo which i tried to design is for sl and target management
sl at candle low or 25 points which ever is more.
target at 35point by modifying sl order to market close.

please please help for is it correct for target at 35point by modifying sl order to market close. i want sl order to be placed at advance with price & trigger and this order should get modify at 35point market close for target (so no margin issue occurs).

sir is it possible that i place order from dhan platform and algo overtakes for sl and target management. for now i have place order from python codes only.

basic logic for the making this is that i dont want to look at my trade after executing order , algo will manage sl and target at same time. so psychology will remain good.

i have used variables for easy change for order details. in future i will try directly fetching for symbol name. but for now i changing manually.

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

client_code = “client_id”
token_id = “token_id”

tsl = Tradehull(client_code, token_id)

try:
# Define the symbol name in one place
symbol_name = ‘CRUDEOIL 16 DEC 6000 CALL’
exchange_name = ‘MCX’
qty = ‘1’
price = ‘151’ # more
trigger_price = ‘150’ # less
sl_points = ‘25’
target_points = ‘35’
minute_time = ‘180’

# Place a Buy Order
buy_entry_orderid = tsl.order_placement(
    symbol_name, exchange_name , qty, price, trigger_price, 'STOPLIMIT', 'BUY', 'MIS'
)

# Get executed price
order_price_response = tsl.get_executed_price(orderid=buy_entry_orderid)
pprint(order_price_response)

if 'executed_price' not in order_price_response:
    raise KeyError("The response does not contain 'executed_price'.")

executed_price = order_price_response['executed_price']
print(f"Executed Price: {executed_price}")

# Calculate Stop Loss (SL) and Target Price
sl_price_1 = round(executed_price - sl_points, 1)

cc_1 = tsl.get_candle_data(symbol_name, exchange_name)
sl_price_2 = round(cc_1['low'], 1)

sl_price = max(sl_price_1, sl_price_2)
target_price = round(executed_price + target_points, 1)

print(f"SL Price: {sl_price}, Target Price: {target_price}")

# Monitor Price
while True:
    try:
        current_price = tsl.get_market_price( symbol_name, exchange_name)
        print(f"Current Price: {current_price}")

        if current_price >= target_price:
            print(f"Target hit! Adjusting SL to market close: {current_price}")
            tsl.modify_order(
                orderid=buy_entry_orderid,
                sl_price=current_price,
                price_type="MARKET"
            )
            break

        # Check Order Time
        order_time = tsl.get_exchange_time(orderid=buy_entry_orderid)
        order_sent_time = datetime.datetime.strptime(order_time, '%Y-%m-%d %H:%M:%S')
        time_spent = (datetime.datetime.now() - order_sent_time).total_seconds() / 60

        if time_spent > minute_time:
            print("Order pending for >180 minutes, canceling...")
            tsl.cancel_order(orderid=buy_entry_orderid)
            break

        time.sleep(1)

    except Exception as loop_error:
        print("Error in price monitoring loop:", str(loop_error))
        traceback.print_exc()
        time.sleep(5)  # Delay before retrying

except Exception as e:
print(“An error occurred:”, str(e))
traceback.print_exc()
pdb.set_trace()

Hello Siddhesh,

I show your message that you can get LTP, historical data and others. But I am facing issue in this. Can you let me know / share me dependency files, which you use in your coding. eg. Dhan_Tradehull_V2.py

Thanks,
Sudip

@Tradehull_Imran sir
Could you guide me on how to continuously fetch the live - market capitalization of any stock? Additionally, is it possible to continuously retrieve the live 52-week high and low prices for that stock?

Can you tell me please which solution works for you

Solution 1

1 Like

Everything is working fine , sir…

Sir, please share the code for the below conditions

  1. what is the code for BETWEEN conditions
    for example , the current candle close should be UP BY ( 0.3 % between 0.4% ) from the pervious close candle

  2. what is the code for pervious N candle,
    lets say, the current candle closed above the ( N candles high or low )

Hi @Tradehull_Imran
I am trying to put SL and target
And how to get trade price

So can you explain that
how can we split our position in to 2 parts
1 - with 1 : 2 target and candle low as SL
2 - trailing stop loss using supertrend

Thank you

1 Like

Check :heavy_check_mark: this

Hi sir please help me on this and one more thing even if i get the data api in market holiday days the api won’t work. That means i didn’t get data from the api. Please help me.

Not getting historical data for lower timeframe 5, 15 minutes however getting ‘DAY’ data, this is happening since last two three days.

hi
@Tradehull_Imran

I tried to solve my querry

how can we split our position in to 2 parts
1 - with 1 : 2 target and candle low as SL
2 - trailing stop loss using supertrend

For that applied following code

if buy1 and buy2 and buy3 and buy4 and buy5 and buy6 and buy7 and no_repeat_order and max_order_limit:
		print(stock_name, "its free, Buy this script")
		
		qty1 	 = 20
		sqf_qty  = 10


		sl_price1          = round((cc_2['low']*0.999),1)
		
		# Strategy 1: 1:2 target with candle low as SL
		target_1 	= round(buy_price - sl_price1) * 2
		sl_price1   = round((cc_2['low']*0.999),1)

		# Strategy 2: Candle low as SL initially, then use supertrend as SL
		sl_price2   = round((cc_2['low']*0.999),1)

		# Simulate the strategy
		    
		# Check for part 1 conditions
		if cc_1['close'] > target_1:
		    print(f"Part 1: Target hit at price {price}. Exiting with profit.")
		    break
		elif cc_1['close'] < sl_price1:
		    print(f"Part 1: Stop-loss hit at price {price}. Exiting with loss.")
		    break
		    


		# Check for part 2 conditions
		if price <= sl_price2:
		    print(f"Part 2: Stop-loss hit at price {price}. Exiting with loss.")
		    break
		elif supertrend > sl_price2:
		    sl_price2  = cc5_2['supertrend']   # Update SL to supertrend
		    print(f"Part 2: SL updated to supertrend value {sl_price2}.")

		print(f"Price: {price}, Part 1 SL: {sl_price1}, Part 2 SL: {sl_price2}")
		


		buy_entry_orderid = tsl.order_placement(stock_name,'NSE', qty1, 0, 0, 'MARKET', 'BUY', 'MIS')
		sl_orderid        = tsl.order_placement(stock_name,'NSE', sqf_qty, 0, sl_price1, 'STOPMARKET', 'SELL', 'MIS')
		traded_wathclist.append(stock_name)

Can you please help me to correct the code

Hi @rahulcse56
Backtesting is a major concept, and its in todo list of videos

Yes strategies can be back-tested, strategy parameters can be optimized, multiple rulesets can be tested to see which one works best.