Give tested code for my strategy

Hi Imran Sir,

As discussed in the class, Please give tested code for calculating ROC.

Reminder!

Can we please have tested code? My strategy is on hold because of this.

Regards, Sobhit

Hi @Sobhit ,

We have started working on this, will let you know once done.

Hi @Sobhit

Check below Tested code

import pdb
import time
import datetime
import traceback
from Dhan_Tradehull import Tradehull
import pandas as pd
from pprint import pprint
import talib
import pandas_ta as ta
import pytz

client_code = 
token_id    = 
tsl         = Tradehull(client_code,token_id)


ce_symbol_name, pe_symbol_name, strike_price = tsl.ATM_Strike_Selection(Underlying='NIFTY', Expiry=0)
last_candle_time = datetime.datetime.now()
last_candle_time = last_candle_time.replace(hour=9, minute=15, second=0, microsecond=0)

ce_data = tsl.get_historical_data(tradingsymbol = ce_symbol_name,exchange = 'NFO',timeframe="1")
pe_data = tsl.get_historical_data(tradingsymbol = pe_symbol_name,exchange = 'NFO',timeframe="1")

print(ce_symbol_name)
print(pe_symbol_name)




while True:

    candle_is_still_running = datetime.datetime.now() < last_candle_time + datetime.timedelta(minutes=1)
    if candle_is_still_running is False:
        ce_data = tsl.get_historical_data(tradingsymbol = ce_symbol_name,exchange = 'NFO',timeframe="1")
        pe_data = tsl.get_historical_data(tradingsymbol = pe_symbol_name,exchange = 'NFO',timeframe="1")
        last_candle_time        = ce_data.iloc[-1]['timestamp'].to_pydatetime().replace(tzinfo=None)        
        continue




    all_ltp_data            = tsl.get_ltp_data(names=[ce_symbol_name, pe_symbol_name])


    if candle_is_still_running:
        ce_ltp                  = all_ltp_data[ce_symbol_name]
        ce_data.iloc[-1, ce_data.columns.get_loc('close')] = ce_ltp

        pe_ltp                  = all_ltp_data[pe_symbol_name]
        pe_data.iloc[-1, pe_data.columns.get_loc('close')] = pe_ltp

        merged_df = pd.merge(ce_data[['timestamp', 'close']], pe_data[['timestamp', 'close']], on='timestamp', suffixes=('_ce', '_pe')).set_index('timestamp')
        merged_df['combined_premium'] = merged_df['close_ce'] + merged_df['close_pe']
        merged_df['ROC'] = talib.ROC(merged_df['combined_premium'], timeperiod=10)

        print(f"ce_ltp {ce_ltp}")
        print(f"pe_ltp {pe_ltp}")
        print(merged_df.tail())



see : Realtimedataframe.mp4 - Google Drive

Thanks for sharing the code, it is appreciated. Now my ask is that here we are calling historical data every minute, What will be the code, if i want to see data updating live (current date, combined ltp, current strike, ROC and Supertrend) on every tick but my trade entry should be on 3 min candle close. Please check my trade condition and confirm if it is good to go.

merged_df = pd.DataFrame({
    'value': [10, 20, 30, 40, 50, 60, 70, 80, 90],
    'time': [
        '2025-01-30 09:10:00', '2025-01-30 09:15:00', '2025-01-30 09:16:00', 
        '2025-01-30 09:17:00', '2025-01-30 09:18:00', '2025-01-30 09:19:00',
        '2025-01-30 09:20:00', '2025-01-30 09:25:00', '2025-01-30 09:30:00'
    ]
})
merged_df['time'] = pd.to_datetime(merged_df['time'])
merged_df.set_index('time', inplace=True)

# Get the first candle (9:15-9:18) and last candle
first_candle_mask = merged_df.index.time.between(datetime.time(9, 15), datetime.time(9, 18))

# Check and fetch values
if first_candle_mask.any():
    First_cc, cc = merged_df[first_candle_mask].iloc[0], merged_df.iloc[-1]
    print(f"First candle: {First_cc}\nLast candle: {cc}")
else:
    print("No data for the first candle range (9:15-9:18)")

In this case we can call 3 min Historical data and update it every second…

Hi Imran Sir, Can you please check my full code and give tested code for my strategy.
Also, suggest where i was wrong.

import pdb
import time
import datetime
import traceback
from Dhan_Tradehull import Tradehull
import pandas as pd
from pprint import pprint
import talib
import pandas_ta as ta
import xlwings as xw
import pytz

book = xw.Book("Straddle.xlsx")
Straddle_chart = book.sheets['Straddle Chart']
config_sheet = book.sheets['Config']
running_orders_sheet = book.sheets['Running Orders']
completed_orders_sheet = book.sheets['Completed Orders']
# Initialize client and connection
client_code = "1100889055"
token_id = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJkaGFuIiwicGFydG5lcklkIjoiIiwiZXhwIjoxNzM5MDk5MTc3LCJ0b2DetlbkNvbnN1bWVyVHlwZSI6IlNFTEYiLCJ3ZWJob29rVXJsIjoiIiwiZGhhbkNsaWVudElkIjoiMTEwMDg4OTA1NSJ9.bX2eeT5ZMHh689KIp_3dUzRzbohivQvgAkrbjZonf2tTq6c4soTcMqnlP6gR4wOIVY1ctBSu_tL4_T51kcFyTA"
tsl = Tradehull(client_code, token_id)




single_order = {'Option name': None,'entry_strike': None,'date': None,'entry_time': None, 'ce_entry_price': None, 'pe_entry_price': None, 'buy_sell': None, 'qty': None, 'sl': None, 'exit_time': None, 'exit_price': None, 'pnl': None, 'remark': None, 'traded': None}
orderbook = {}
completed_orders = {'Option name': None,'entry_strike': None, 'date': None, 'entry_time': None, 'ce_entry_price': None, 'pe_entry_price': None, 'buy_sell': None, 'qty': None, 'sl': None, 'exit_time': None, 'exit_price': None, 'pnl': None, 'remark': None, 'traded': None}

watchlist = ['NIFTY']
all_dataframes = []
completed_orders = []
reentry          = "yes" #"yes/no"
# Initialize merged_df outside the if block
merged_df = None
# Initialize Supertrend outside the if block
Supertrend = None

ce_name, pe_name, strike_price = tsl.ATM_Strike_Selection(Underlying='NIFTY', Expiry=0)
last_candle_time = datetime.datetime.now()
last_candle_time = last_candle_time.replace(hour=9, minute=15, second=0, microsecond=0)

ce_data = tsl.get_historical_data(tradingsymbol=ce_name, exchange='NFO', timeframe="1")
pe_data = tsl.get_historical_data(tradingsymbol=pe_name, exchange='NFO', timeframe="1")

print(ce_name)
print(pe_name)

bot_token        = "8009492753:AAEOEVp5v86ce4jcJuNXnv0_AAT4JfzNPGA"
receiver_chat_id = "876625569"


for name in watchlist:
    orderbook[name] = single_order.copy()

while True:

    print("starting while Loop \n\n")

    current_time = datetime.datetime.now().time()
    if current_time < datetime.time(13, 55):
        print(f"Wait for market to start", current_time)
        time.sleep(1)
        continue

    if current_time > datetime.time(23, 15):
        order_details = tsl.cancel_all_orders()
        print(f"Market over Closing all trades !! Bye Bye See you Tomorrow", current_time)
        pdb.set_trace()
        break



    for name in watchlist:
        # ------------------------------------- UPDATE SHEET -------------------------------------
        try:
            # Convert orderbook to DataFrame with explicit index
            orderbook_df = pd.DataFrame.from_dict(orderbook, orient='index').reset_index()
            running_orders_sheet.range('A1').value = orderbook_df
            completed_orders_df = pd.DataFrame(completed_orders)
            completed_orders_sheet.range('A1').value = completed_orders_df
        except Exception as e:
            print("Error in updating running orders sheet", e)

        # ------------------------------------- GET DATA -------------------------------------

        candle_is_still_running = datetime.datetime.now() < last_candle_time + datetime.timedelta(minutes=1)
        ce_name, pe_name, strike_price = tsl.ATM_Strike_Selection(Underlying='NIFTY', Expiry=0)
        if candle_is_still_running is False:
            ce_data = tsl.get_historical_data(tradingsymbol = ce_name,exchange = 'NFO',timeframe="1")
            pe_data = tsl.get_historical_data(tradingsymbol = pe_name,exchange = 'NFO',timeframe="1")
            last_candle_time        = ce_data.iloc[-1]['timestamp'].to_pydatetime().replace(tzinfo=None)        
            continue

        all_ltp_data            = tsl.get_ltp_data(names=[ce_name, pe_name])

        if candle_is_still_running:
            ce_ltp                  = all_ltp_data[ce_name]
            ce_data.iloc[-1, ce_data.columns.get_loc('close')] = ce_ltp

            pe_ltp                  = all_ltp_data[pe_name]
            pe_data.iloc[-1, pe_data.columns.get_loc('close')] = pe_ltp

            merged_df = pd.merge(ce_data[['timestamp', 'close']], pe_data[['timestamp', 'close']], on='timestamp', suffixes=('_ce', '_pe')).set_index('timestamp')
            merged_df['combined_premium'] = merged_df['close_ce'] + merged_df['close_pe']
            # Calculate OHLC for combined premium
            merged_df['combined_premium_high'] = merged_df['combined_premium'].rolling(window=1).max()
            merged_df['combined_premium_low'] = merged_df['combined_premium'].rolling(window=1).min()
            merged_df['combined_premium_open'] = merged_df['combined_premium'].shift(1)
            merged_df['combined_premium_close'] = merged_df['combined_premium']
            
        merged_df['ROC'] = talib.ROC(merged_df['combined_premium'], timeperiod=9)
            # Calculate Supertrend using pandas_ta
        Supertrend = ta.supertrend(merged_df['combined_premium_high'], merged_df['combined_premium_low'], merged_df['combined_premium_close'], 10, 2)
        merged_df = pd.concat([merged_df, Supertrend], axis=1, join='inner')
        # Remove .values from numpy float values since they don't have that attribute
        combined_premium_value = merged_df['combined_premium'].iloc[-1]
        roc_value = merged_df['ROC'].iloc[-1]
        supertrend_value = Supertrend['SUPERTd_10_2.0'].iloc[-1]
        
        data_to_write = [str(current_time), combined_premium_value, strike_price, roc_value, supertrend_value]

        print(f"ce_ltp {ce_ltp}")
        print(f"pe_ltp {pe_ltp}")
        print(f'Supertrend {supertrend_value}')
        

        last_row = 2
        while Straddle_chart.range(f'A{last_row}').value is not None:
            last_row += 1
        if last_row > 30000:  # Safety limit
            last_row = 2  # Reset to top if sheet is full
            break

        # Add strike change message if strike price changed
        if last_row > 2 and Straddle_chart.range(f'C{last_row-1}').value != strike_price:
            data_to_write.append("Strike change to " + str(strike_price))
            print(f"Strike price changed from {Straddle_chart.range(f'C{last_row-1}').value} to {strike_price}")
        else:
            data_to_write.append("")
        Straddle_chart.range(f'A{last_row}:E{last_row}').value = data_to_write
                
        # Initialize variables with default values before try block
        tc1 = tc2 = tc3 = False

        try:
            # Get first and current candle for 3-minute timeframe
            First_cc = merged_df.iloc[0] # First candle of 1-min period
            cc = merged_df.iloc[-1] # Current candle of 1-min period
            
            # Check if we're at the 3-min candle close
            current_minute = current_time.minute
            if current_minute % 3 != 0:  # Only take trade at 3-min candle close
                continue
            

            tc1 = Supertrend['SUPERTd_10_2.0'].values[-1] == -1
            tc2 = current_time > datetime.time(9, 15) and current_time < datetime.time(23, 15)
            tc3 = orderbook[name]['traded'] is None
        except Exception as e:
            print("Error accessing data:", e)
            continue

        # Add a check before using Supertrend
        if Supertrend is not None:
            ec1 = Supertrend['SUPERTd_10_2.0'].values[-1] == 1
        else:
            ec1 = False  # or handle this case as needed
        # Check if entry_strike exists before comparing
        # Check if entry strike exists and has changed
        ec2 = False
        if orderbook[name]['traded'] == "yes" and 'entry_strike' in orderbook[name]:
            entry_strike = orderbook[name]['entry_strike']
            if entry_strike != strike_price:
                print(f"ATM strike changed from {entry_strike} to {strike_price}")
                ec2 = True
        ec3 = current_time >= datetime.time(15, 15)  # Exit at 3:15 PM
        ec4 = orderbook[name]['traded'] == "yes"  # Check if trade is active

        if tc1 and tc2 and tc3:
            print("Trade condition met. Placing order...Short Straddle")
            margin_avialable = tsl.get_balance()
            margin_required  = 200000

            if margin_avialable < margin_required:
                print(f"Less margin, not taking order : margin_avialable is {margin_avialable} and margin_required is {margin_required} for {name}")
                continue
            orderbook[name]['name']           = name
            orderbook[name]['date']           = str(current_time.date())
            orderbook[name]['entry_time']     = str(current_time.time())[:8]
            orderbook[name]['buy_sell']       = "SELL"
            orderbook[name]['qty']            = ce_qty or pe_qty

            try:
                ce_lot_size = tsl.get_lot_size(tradingsymbol=ce_name)
                pe_lot_size = tsl.get_lot_size(tradingsymbol=pe_name)

                # Set the quantity to 1 lot for both CE and PE
                ce_qty = ce_lot_size * 1
                pe_qty = pe_lot_size * 1

                
                ce_entry_ordrid                     = tsl.order_placement(tradingsymbol=ce_name, exchange='NFO', quantity=orderbook[name]['qty'], price=ce_ltp, trigger_price=0, order_type='MARKET', transaction_type='SELL', trade_type='MIS', after_market_order=True)
                orderbook[name]['entry_price']   = all_ltp_data[ce_name]
                pe_entry_ordrid                      = tsl.order_placement(tradingsymbol=pe_name, exchange='NFO', quantity=orderbook[name]['qty'], price=pe_ltp, trigger_price=0, order_type='MARKET', transaction_type='SELL', trade_type='MIS', after_market_order=True)
                orderbook[name]['entry_price']   = all_ltp_data[pe_name]
                orderbook[name]['ce_entry_ordrid']   = ce_entry_ordrid
                orderbook[name]['pe_entry_ordrid']   = pe_entry_ordrid
                orderbook[name]['entry_time']        = str(datetime.datetime.now().time())[:8]
                orderbook[name]['entry_datetime']    = datetime.datetime.now()
                orderbook[name]['traded']            = "yes"

                message = "\n".join(f"'{key}': {repr(value)}" for key, value in orderbook[name].items())
                message = f"Entry_done {name} \n\n {message}"
                tsl.send_telegram_alert(message=message,receiver_chat_id=receiver_chat_id,bot_token=bot_token)

            except Exception as e:
                print(f"Error placing orders: {str(e)}")
                print(f"Traceback: {traceback.format_exc()}")

        else:
            print("Trade condition not met. Skipping entry.")

        # ------------------------------------- Exit Condition -------------------------------------
        if (ec1 or ec2 or ec3) and ec4:
            print("Exit condition met. Closing straddle position...", strike_price)
            try:
                # Store exit details
                current_trade                   = orderbook[name].copy()
                orderbook[name]['ce_name']      = ce_name
                orderbook[name]['pe_name']      = pe_name
                orderbook[name]['buy_sell']     = "BUY" 
                orderbook[name]['date']         = str(datetime.datetime.now().date())
                orderbook[name]['exit_time']    = str(datetime.datetime.now().time())[:8]
                orderbook[name]['exit_datetime']= datetime.datetime.now()
                orderbook[name]['qty']          = ce_qty or pe_qty
                # Place sell orders to close straddle position
                ce_exit_ordrid                  = tsl.order_placement(tradingsymbol=orderbook[name]['ce_name'], exchange='NFO', quantity=orderbook[name]['qty'], price=0, trigger_price=0, order_type='MARKET', transaction_type='BUY', trade_type='MIS')
                orderbook[name]['exit_price']   = all_ltp_data[ce_name]
                pe_exit_ordrid                  = tsl.order_placement(tradingsymbol=orderbook[name]['pe_name'], exchange='NFO', quantity=orderbook[name]['qty'], price=0, trigger_price=0, order_type='MARKET', transaction_type='BUY', trade_type='MIS')
                orderbook[name]['exit_price']   = all_ltp_data[pe_name]

                # Store exit order IDs
                orderbook[name]['ce_exit_ordrid'] = ce_exit_ordrid
                orderbook[name]['pe_exit_ordrid'] = pe_exit_ordrid
                orderbook[name]['traded']         = None  # Reset traded status
            except Exception as e:
                print(f"Error closing straddle position: {str(e)}")
                print(f"Traceback: {traceback.format_exc()}")

        if orderbook[name]['traded'] == "yes":
            sold   = orderbook[name]['buy_sell'] == "SELL"
            bought = orderbook[name]['buy_sell'] == "BUY"
 
            if sold and bought:
                orderbook[name]['pnl'] = (orderbook[name]['ce_entry_price'] - orderbook['name']['ce_exit_price']) * orderbook[name]['qty'] + (orderbook[name]['pe_entry_price'] - orderbook['name']['pe_exit_price']) * orderbook[name]['qty']
                completed_orders.append(orderbook[name])
                orderbook[name] = {x:None for x in orderbook[name]}
        if reentry == "yes":
            completed_orders.append(orderbook[name])
            orderbook[name] = None

Hi @Sobhit
Do run the code and share the error screenshot faced.

Getting below error.

“ce_ltp 116.05
pe_ltp 144.3
Supertrend 1
Error accessing data: ‘NoneType’ object is not subscriptable
starting while Loop”

Also, please check why my running order book not getting updated, further, please check this part of my code if it is rightly written.

  1. It seems the code is working fine to get the supertrend value:

  2. Running orders will get updated only if orderbook_df is not empty

  3. Code seems to be okay.

Can we call 3 minute historical data? Can you suggest the necessary changes in my code to take trade at 3 minutes candle close and exit the trade only at 3 minute candle close.

import pdb
import time
import datetime
import traceback
from Dhan_Tradehull import Tradehull
import pandas as pd
from pprint import pprint
import talib
import pandas_ta as ta
import xlwings as xw
import pytz

# Open the Excel workbook and necessary sheets
book = xw.Book("Straddle.xlsx")
Straddle_chart = book.sheets['Straddle Chart']
config_sheet = book.sheets['Config']
running_orders_sheet = book.sheets['Running Orders']
completed_orders_sheet = book.sheets['Completed Orders']

# Initialize client and connection
client_code = "11008890xx"
token_id = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJkaGFuIiwicGFydG5lcklkIjoiIiwiZXhwIjoxNzM5MDk5MTc3LCJ0b2tlbkNvbnNdhf1bWVyVHlwZSI6IlNFTEYiLCJ3ZWJob29rVXJsIjoiIiwiZGhhbkNsaWVudElkIjoiMTEwMDg4OTA1NSJ9.bX2eeT5ZMHh689KIp_3dUzRzbohivQvgAkrbjZonf2tTq6c4soTcMqnlP6gR4wOIVY1ctBSu_tL4_T51kcFyTA"
tsl = Tradehull(client_code, token_id)

# Define the order structure
single_order = {'Option name': None,'entry_strike': None,'date': None,'entry_time': None, 'ce_entry_price': None, 'pe_entry_price': None, 'combined_premium_entry_price': None, 'buy_sell': None, 'exit_time': None, 'ce_exit_price': None, 'pe_exit_price': None, 'combined_premium_exit_price': None,'ce_qty': None, 'pe_qty': None, 'pnl': None, 'remark': None, 'traded': None}
orderbook = {}
completed_orders = {'Option name': None,'entry_strike': None,'date': None,'entry_time': None, 'ce_entry_price': None, 'pe_entry_price': None, 'combined_premium_entry_price': None, 'buy_sell': None, 'exit_time': None, 'ce_exit_price': None, 'pe_exit_price': None, 'combined_premium_exit_price': None,'ce_qty': None, 'pe_qty': None, 'pnl': None, 'remark': None, 'traded': None}



watchlist = ['NIFTY']
all_dataframes = []
completed_orders = []
reentry = "yes"  # "yes/no"
merged_df = None
Supertrend = None

# Initialize trading symbols
ce_name, pe_name, strike_price = tsl.ATM_Strike_Selection(Underlying='NIFTY', Expiry=0)
last_candle_time = datetime.datetime.now().replace(hour=9, minute=15, second=0, microsecond=0)

# Initial data fetching
ce_data = tsl.get_historical_data(tradingsymbol=ce_name, exchange='NFO', timeframe="1")
pe_data = tsl.get_historical_data(tradingsymbol=pe_name, exchange='NFO', timeframe="1")

# Print the option names for debugging
print(ce_name)
print(pe_name)

# Telegram bot configuration for alerts
bot_token = "8009492753:AAEOEVp5v86ce4jcJuNXnv0_AAT4JfzNPGA"
receiver_chat_id = "876625569"

# Initialize the orderbook for each watchlist item
for name in watchlist:
    orderbook[name] = single_order.copy()


# Main loop
while True:
    print("starting while Loop \n\n")
    current_time = datetime.datetime.now().time()
    current_datetime = datetime.datetime.now()

    if current_time < datetime.time(9, 15):
        print(f"Wait for market to start", current_time)
        time.sleep(60)
        continue

    if current_time > datetime.time(15, 25):
        order_details = tsl.cancel_all_orders()
        print(f"Market over Closing all trades !! Bye Bye See you Tomorrow", current_time)
        pdb.set_trace()
        break

    # Check if 3-minute candle has closed

    # Track 3-minute candle time
    for name in watchlist:
        try:
            # Update the Excel sheets for running and completed orders
            orderbook_df = pd.DataFrame.from_dict(orderbook, orient='index').reset_index()
            # Convert DataFrame to a list of lists for Excel
            orderbook_values = [orderbook_df.columns.tolist()] + orderbook_df.values.tolist()
            running_orders_sheet.range('A1').value = orderbook_values

            # Handle completed orders
            if completed_orders:  # Only update if there are completed orders
                completed_orders_df = pd.DataFrame(completed_orders)
                completed_values = [completed_orders_df.columns.tolist()] + completed_orders_df.values.tolist()
                completed_orders_sheet.range('A1').value = completed_values
        except Exception as e:
            print(f"Error in updating Excel sheets: {str(e)}")
            print(f"Traceback: {traceback.format_exc()}")

        # Get new data
        candle_is_still_running = datetime.datetime.now() < last_candle_time + datetime.timedelta(minutes=1)
        ce_name, pe_name, strike_price = tsl.ATM_Strike_Selection(Underlying='NIFTY', Expiry=0)
        if not candle_is_still_running:
            ce_data = tsl.get_historical_data(tradingsymbol=ce_name, exchange='NFO', timeframe="1")
            pe_data = tsl.get_historical_data(tradingsymbol=pe_name, exchange='NFO', timeframe="1")
            last_candle_time = ce_data.iloc[-1]['timestamp'].to_pydatetime().replace(tzinfo=None)
            continue

        all_ltp_data = tsl.get_ltp_data(names=[ce_name, pe_name])

        if candle_is_still_running:
            ce_ltp = all_ltp_data[ce_name]
            ce_data.iloc[-1, ce_data.columns.get_loc('close')] = ce_ltp

            pe_ltp = all_ltp_data[pe_name]
            pe_data.iloc[-1, pe_data.columns.get_loc('close')] = pe_ltp

            merged_df = pd.merge(ce_data[['timestamp', 'close']], pe_data[['timestamp', 'close']], on='timestamp', suffixes=('_ce', '_pe')).set_index('timestamp')
            merged_df['combined_premium'] = merged_df['close_ce'] + merged_df['close_pe']
            merged_df['combined_premium_high'] = merged_df['combined_premium'].rolling(window=1).max()
            merged_df['combined_premium_low'] = merged_df['combined_premium'].rolling(window=1).min()
            merged_df['combined_premium_open'] = merged_df['combined_premium'].shift(1)
            merged_df['combined_premium_close'] = merged_df['combined_premium']

        merged_df['ROC'] = talib.ROC(merged_df['combined_premium'], timeperiod=9)
        Supertrend = ta.supertrend(merged_df['combined_premium_high'], merged_df['combined_premium_low'], merged_df['combined_premium_close'], 10, 2)
        merged_df = pd.concat([merged_df, Supertrend], axis=1, join='inner')

        combined_premium_value = merged_df['combined_premium'].iloc[-1]
        roc_value = merged_df['ROC'].iloc[-1]
        supertrend_value = Supertrend['SUPERTd_10_2.0'].iloc[-1]

        data_to_write = [str(current_time), combined_premium_value, strike_price, roc_value, supertrend_value]

        print(f"ce_ltp {ce_ltp}")
        print(f"pe_ltp {pe_ltp}")
        print(f'Supertrend {supertrend_value}')

        last_row = 2
        while Straddle_chart.range(f'A{last_row}').value is not None:
            last_row += 1
        if last_row > 30000:
            last_row = 2  # Reset to top if sheet is full
            break

        # Add strike change message if strike price changed
        if last_row > 2 and Straddle_chart.range(f'C{last_row-1}').value != strike_price:
            data_to_write.append("Strike change to " + str(strike_price))
            print(f"Strike price changed from {Straddle_chart.range(f'C{last_row-1}').value} to {strike_price}")
        else:
            data_to_write.append("")
        Straddle_chart.range(f'A{last_row}:E{last_row}').value = data_to_write




        
        tc1 = Supertrend['SUPERTd_10_2.0'].iloc[-1] == -1
        tc2 = current_time > datetime.time(9, 15) and current_time < datetime.time(23, 15)
        tc3 = orderbook[name] and orderbook[name]['traded'] is None

            # Trade conditions met - checking on 3 min timeframe
        # Check if current time is at 3-minute candle close
        current_minute = current_time.minute
        check_conditions = False
        if current_minute % 3 == 0 and current_time.second == 0:
            check_conditions = True
            print(f"Checking conditions at {current_time} - 3 min candle close")


        if tc1 and tc2 and tc3 and check_conditions:
            print("Trade condition met. Placing order...Short Straddle")
            ce_lot_size = tsl.get_lot_size(tradingsymbol=ce_name)
            pe_lot_size = tsl.get_lot_size(tradingsymbol=pe_name)

                # Set the quantity to 1 lot for both CE and PE
            ce_qty = ce_lot_size * 4
            pe_qty = pe_lot_size * 4
            orderbook[name]['Option name'] = name
            orderbook[name]['entry_strike'] = strike_price
            orderbook[name]['date'] = str(datetime.datetime.now().date())
            orderbook[name]['buy_sell'] = "SELL"
            orderbook[name]['ce_qty'] = ce_qty
            orderbook[name]['pe_qty'] = pe_qty


            try:
                ce_entry_ordrid = 111111111
                orderbook[name]['ce_entry_price'] = all_ltp_data[ce_name]
                pe_entry_ordrid = 222222222
                orderbook[name]['pe_entry_price'] = all_ltp_data[pe_name]
                orderbook[name]['combined_premium_entry_price'] = all_ltp_data[ce_name] + all_ltp_data[pe_name]
                orderbook[name]['ce_entry_ordrid'] = ce_entry_ordrid
                orderbook[name]['pe_entry_ordrid'] = pe_entry_ordrid
                orderbook[name]['entry_time'] = str(datetime.datetime.now().time())[:8]
                orderbook[name]['traded'] = "yes"

                message = "\n".join(f"'{key}': {repr(value)}" for key, value in orderbook[name].items())
                message = f"Entry_done {name} \n\n {message}"
                tsl.send_telegram_alert(message=message, receiver_chat_id=receiver_chat_id, bot_token=bot_token)

            except Exception as e:
                print(f"Error placing orders: {str(e)}")
                print(f"Traceback: {traceback.format_exc()}")
        else:
            print("Trade condition not met. Skipping entry.")

        # Exit conditions
        ec1 = Supertrend['SUPERTd_10_2.0'].iloc[-1] == 1
        ec2 = False
        if orderbook[name]['entry_strike'] is not None:
            ec2 = abs(orderbook[name]['entry_strike'] - strike_price) >= 50
        ec3 = current_time >= datetime.time(23, 15)
        ec4 = orderbook[name]['traded'] == "yes"


        if (ec1 or ec2 or ec3) and ec4 and check_conditions:
            print("Exit condition met. Closing straddle position...", "Reason:", "Supertrend == 1" if ec1 else "Strike Price Difference >= 50" if ec2 else "Time >= 23:15")
            try:
                # Store exit details
                
                orderbook[name]['Option name'] = name
                orderbook[name]['entry_strike'] = strike_price
                orderbook[name]['buy_sell'] = "BUY"
                orderbook[name]['date'] = str(datetime.datetime.now().date())

                orderbook[name]['exit_time'] = str(datetime.datetime.now().time())[:8]
                orderbook[name]['exit_datetime'] = datetime.datetime.now()
                orderbook[name]['ce_qty'] = ce_qty
                orderbook[name]['pe_qty'] = pe_qty
                # Place sell orders to close straddle position
                ce_exit_ordrid = 333333333

                orderbook[name]['ce_exit_price'] = all_ltp_data[ce_name]
                pe_exit_ordrid = 444444444
                orderbook[name]['pe_exit_price'] = all_ltp_data[pe_name]
                orderbook[name]['combined_premium_exit_price'] = all_ltp_data[ce_name] + all_ltp_data[pe_name]
                orderbook[name]['ce_exit_ordrid'] = ce_exit_ordrid
                orderbook[name]['pe_exit_ordrid'] = pe_exit_ordrid
                orderbook[name]['traded'] = None  # Reset traded status

                # Calculate PnL after closing straddle position
                ce_pnl = (orderbook[name]['ce_entry_price'] - orderbook[name]['ce_exit_price']) * orderbook[name]['ce_qty']
                pe_pnl = (orderbook[name]['pe_entry_price'] - orderbook[name]['pe_exit_price']) * orderbook[name]['pe_qty']
                total_pnl = ce_pnl + pe_pnl
                orderbook[name]['pnl'] = total_pnl

                # Send PnL alert
                pnl_message = f"Trade closed for {name}\nEntry Strike: {orderbook[name]['entry_strike']}\nCE PnL: {ce_pnl:.2f}\nPE PnL: {pe_pnl:.2f}\nTotal PnL: {total_pnl:.2f}"
                tsl.send_telegram_alert(message=pnl_message, receiver_chat_id=receiver_chat_id, bot_token=bot_token)

                # Add to completed orders and reset orderbook
                completed_orders.append(orderbook[name].copy())
                orderbook[name] = single_order.copy()

            except Exception as e:
                print(f"Error closing straddle position: {str(e)}")
                print(f"Traceback: {traceback.format_exc()}")

            if reentry == "yes":
                completed_orders.append(orderbook[name])
                orderbook[name] = single_order.copy()

Hi @Sobhit ,

Currently, Dhan does not support 3-minute data. It only provides the following timeframes: ['1', '5', '15', '25', '60', 'DAY'].

So can’t i take trade on 3 minute candle close? If yes, what modification do i need to make in my trade entry and exit conditions?

Hi @Sobhit,

To use 3-minute candle data, you can use one minute data and resample the data using python.