Crude oil Atm Selection

import pdb
import time
import datetime
import traceback
from Dhan_Tradehull import Tradehull
import pandas as pd
import pprint
from pandas_ta.overlap import supertrend
import talib
import pandas_ta as pta
import pandas_ta as ta
import warnings

warnings.filterwarnings("ignore")

# --------------- dhan login ----------------
client_code = 
token_id = 
tsl = Tradehull(client_code, token_id)

traded = "no"
trade_info = {"options_name": None, "qty": None, "sl": None, "CE_PE": None, "symbol": None}
watchlist = ["CRUDEOIL1!", "NATURALGAS1!"]

while True:
    time.sleep(2)

    for symbol in watchlist:
        current_time = datetime.datetime.now()
#        index_chart = tsl.get_historical_data(tradingsymbol=symbol, exchange='MCX', timeframe="1")
        index_chart  = tsl.get_historical_data(tradingsymbol = symbol,exchange = 'MCX' ,timeframe="1") 
        #print (index_chart)

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


        # vwap
        #index_chart.set_index(pd.DatetimeIndex(index_chart['timestamp']), inplace=True)
       # typical_price = (index_chart['high'] + index_chart['low'] + index_chart['close']) / 3
       # index_chart['vwap'] = (typical_price * index_chart['volume']).cumsum() / index_chart['volume'].cumsum()

        # Supertrend
        #supertrend_df = ta.supertrend(index_chart['high'], index_chart['low'], index_chart['close'], length=10, multiplier=2.0)
        #index_chart['supertrend'] = supertrend_df['SUPERT_10_2.0']
        #index_chart = pd.concat([index_chart, supertrend_df], 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()

    # ---------------- PMA ----------------
        length = 20
        palen = 30
        max_acc = 0.2

    # Base EMA
        index_chart['ma'] = index_chart['close'].ewm(span=length, adjust=False).mean()

        roc_ma = index_chart['ma'].diff()
        roc_src = index_chart['close'].diff()

        step = max_acc / palen
        acc = [0] * len(index_chart)

        for i in range(palen, len(index_chart)):
            acc_val = 0
        for j in range(palen):
            if abs(roc_src.iloc[i-j]) > abs(roc_ma.iloc[i-j]):
                acc_val += step
            else:
                acc_val -= step
        acc[i] = acc_val

        index_chart['acc'] = acc

    # Volatility
        index_chart['vol'] = index_chart['ma'].rolling(palen).std()

    # Direction
        avg_roc = roc_ma.rolling(palen).mean()
        direction_val = avg_roc.apply(lambda x: 1 if x > 0 else (-1 if x < 0 else 0))

    # PMA
        index_chart['pma_raw'] = index_chart['ma'] + (index_chart['acc'] * index_chart['vol'] * direction_val)

        sqrt_len = int(length ** 0.5)
        pma_ma = index_chart['pma_raw'].ewm(span=sqrt_len, adjust=False).mean()
        index_chart['pma'] = pma_ma.ewm(span=sqrt_len, adjust=False).mean()

        index_chart['pma_slope'] = index_chart['pma'] - index_chart['pma'].shift(1)
        

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

      #  print (first_candle, second_candle, running_candle)

        # ---------- SELL ENTRY CONDITIONS ----------
        #sc1 = first_candle['close'] < first_candle['vwap']
        #sc2 = first_candle['close'] < first_candle['SUPERT_10_2.0']
        sc2 = first_candle['close'] < first_candle['pma']
        #sc3 = first_candle['close'] < first_candle['vwma']
        sc3 = first_candle['pma_slope'] < 0
        #sc4 = first_candle['rsi'] > 20
        #sc5 = second_candle['volume'] > 500
        #sc5 = second_candle['volume'] > 50000
        sc6 = traded == "no"
        print("SELL ", current_time, sc2, sc3, sc6)

        if sc2 and sc3 and sc6:
#        if sc1 and sc2 and sc3 and sc4 and sc5 and sc6:

            print("Sell Signal Formed")
            ce_name, pe_name, strike = tsl.ATM_Strike_Selection(Underlying= symbol, Expiry= 2)                                                                
            lot_size = tsl.get_lot_size(pe_name) * 5
            entry_orderid = tsl.order_placement(pe_name, 'NFO', lot_size, 0, 0, 'MARKET', 'BUY', 'MIS')
            traded = "yes"
            print(ce_name, pe_name, strike, lot_size, entry_orderid, trade_info)

            # Ensure sl is stored as a float
            trade_info['options_name'] = pe_name
            trade_info['qty'] = lot_size
            trade_info['sl'] = float(first_candle['high'])  # Convert to float
            trade_info['CE_PE'] = "PE"
            trade_info['symbol'] = symbol  # Store the traded symbol

        # ---------- EXIT CHECK (only for the traded symbol) ----------
        if traded == "yes":
            # Get fresh data for the traded symbol only
            exit_chart = tsl.get_historical_data(tradingsymbol=trade_info['symbol'], exchange='NFO', timeframe="5")
            exit_chart['rsi'] = talib.RSI(exit_chart['close'], timeperiod=14)
            exit_chart.set_index(pd.DatetimeIndex(exit_chart['timestamp']), inplace=True)
            typical_price = (exit_chart['high'] + exit_chart['low'] + exit_chart['close']) / 3
            exit_chart['vwap'] = (typical_price * exit_chart['volume']).cumsum() / exit_chart['volume'].cumsum()
            supertrend_df = ta.supertrend(exit_chart['high'], exit_chart['low'], exit_chart['close'], length=10, multiplier=2.0)
            exit_chart = pd.concat([exit_chart, supertrend_df], axis=1, join='inner')
            current_candle = exit_chart.iloc[-1]

            # Get current LTP of the option
            ltp_data = tsl.get_ltp_data(names=[trade_info['options_name']])
            index_ltp = float(ltp_data[trade_info['options_name']])  # Extract float value

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

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

                if sl_hit or tg_hit:
                    remark = "SL Hit" if sl_hit else "Target Hit"
                    print(f"EXIT TRIGGERED: {remark}")
                    exit_orderid = tsl.order_placement(trade_info['options_name'], 'NFO', trade_info['qty'], 0, 0, 'MARKET', 'SELL', 'MIS')
                    pdb.set_trace()

                    log_data = pd.DataFrame([{
                        "timestamp": datetime.datetime.now(),
                        "symbol": trade_info['symbol'],
                        "options_name": trade_info['options_name'],
                        "qty": trade_info['qty'],
                        "ltp": index_ltp,
                        "sl": trade_info['sl'],
                        "CE_PE": trade_info['CE_PE'],
                        "order_id": exit_orderid,
                        "remark": remark
                    }])
                    log_data.to_csv("trade_log.csv", mode="a", header=not pd.io.common.file_exists("trade_log.csv"), index=False)

                    # Reset trade flag after exit
                    traded = "no"
                    trade_info = {"options_name": None, "qty": None, "sl": None, "CE_PE": None, "symbol": None}

error:- Unable to fetch correct expiry

Hi @dattaswaami
can you please share the error as well for this one

also in watchlist do remove ! mark

watchlist = ["CRUDEOIL1!", "NATURALGAS1!"] # wrong
watchlist = ["CRUDEOIL", "NATURALGAS"] # right

Sir this problem is solved but in the following code

import pdb
import time
import datetime
import traceback
from Dhan_Tradehull import Tradehull
import pandas as pd
import pprint
from pandas_ta.overlap import supertrend
import talib
import pandas_ta as pta
import pandas_ta as ta
import warnings

warnings.filterwarnings("ignore")

# --------------- dhan login ----------------
client_code = 
token_id = 
tsl = Tradehull(client_code, token_id)

traded = "no"
trade_info = {"options_name": None, "qty": None, "sl": None, "CE_PE": None, "symbol": None}
watchlist = ["NIFTY"]
expiry = [1]  

while True:
    time.sleep(2)

    for symbol in watchlist:
        current_time = datetime.datetime.now()
#        index_chart = tsl.get_historical_data(tradingsymbol=symbol, exchange='MCX', timeframe="1")
        index_chart  = tsl.get_historical_data(tradingsymbol = symbol,exchange = 'INDEX' ,timeframe="1") 
        #print (index_chart)

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


        # vwap
        #index_chart.set_index(pd.DatetimeIndex(index_chart['timestamp']), inplace=True)
       # typical_price = (index_chart['high'] + index_chart['low'] + index_chart['close']) / 3
       # index_chart['vwap'] = (typical_price * index_chart['volume']).cumsum() / index_chart['volume'].cumsum()

        # Supertrend
        #supertrend_df = ta.supertrend(index_chart['high'], index_chart['low'], index_chart['close'], length=10, multiplier=2.0)
        #index_chart['supertrend'] = supertrend_df['SUPERT_10_2.0']
        #index_chart = pd.concat([index_chart, supertrend_df], 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()

    # ---------------- PMA ----------------
        length = 20
        palen = 30
        max_acc = 0.2

    # Base EMA
        index_chart['ma'] = index_chart['close'].ewm(span=length, adjust=False).mean()

        roc_ma = index_chart['ma'].diff()
        roc_src = index_chart['close'].diff()

        step = max_acc / palen
        acc = [0] * len(index_chart)

        for i in range(palen, len(index_chart)):
            acc_val = 0
        for j in range(palen):
            if abs(roc_src.iloc[i-j]) > abs(roc_ma.iloc[i-j]):
                acc_val += step
            else:
                acc_val -= step
        acc[i] = acc_val

        index_chart['acc'] = acc

    # Volatility
        index_chart['vol'] = index_chart['ma'].rolling(palen).std()

    # Direction
        avg_roc = roc_ma.rolling(palen).mean()
        direction_val = avg_roc.apply(lambda x: 1 if x > 0 else (-1 if x < 0 else 0))

    # PMA
        index_chart['pma_raw'] = index_chart['ma'] + (index_chart['acc'] * index_chart['vol'] * direction_val)

        sqrt_len = int(length ** 0.5)
        pma_ma = index_chart['pma_raw'].ewm(span=sqrt_len, adjust=False).mean()
        index_chart['pma'] = pma_ma.ewm(span=sqrt_len, adjust=False).mean()

        index_chart['pma_slope'] = index_chart['pma'] - index_chart['pma'].shift(1)
        

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

        close = float(running_candle['close'])
        pma = float(running_candle['pma'])
        slope = float(running_candle['pma_slope'])

      #  print (first_candle, second_candle, running_candle)

        # ---------- SELL ENTRY CONDITIONS ----------
        #sc1 = first_candle['close'] < first_candle['vwap']
        #sc2 = first_candle['close'] < first_candle['SUPERT_10_2.0']
        sc2 = first_candle['close'] < first_candle['pma']
        #sc3 = first_candle['close'] < first_candle['vwma']
        sc3 = first_candle['pma_slope'] < 0
        #sc4 = first_candle['rsi'] > 20
        #sc5 = second_candle['volume'] > 500
        #sc5 = second_candle['volume'] > 50000
        sc6 = traded == "no"
        print("SELL ", current_time, sc2, sc3, sc6)

        if sc2 and sc3 and sc6:
#        if sc1 and sc2 and sc3 and sc4 and sc5 and sc6:
          for expiry in expiry:  
            print("Sell Signal Formed")
            ce_name, pe_name, strike = tsl.ATM_Strike_Selection(Underlying= symbol, Expiry= expiry)                                                                
            lot_size = tsl.get_lot_size(pe_name) * 5
            entry_orderid = tsl.order_placement(pe_name, 'NFO', lot_size, 0, 0, 'MARKET', 'BUY', 'MIS')
            traded = "yes"
            print(ce_name, pe_name, strike, lot_size, entry_orderid, trade_info)
            
            
            
            
      #      ce_name, pe_name, strike = tsl.ATM_Strike_Selection(Underlying= symbol, Expiry="1") 
  #          CE_name, PE_name, CE_ATM_price, PE_ATM_price = tsl.ATM_Strike_Selection(Underlying= symbol, Expiry="1", ATM="1")

         # ---------- BUY ENTRY CONDITIONS ----------
        #bc1 = first_candle['close'] > first_candle['vwap']
        #bc2 = first_candle['close'] < first_candle['SUPERT_10_2.0']
        bc2 = first_candle['close'] >  first_candle['pma']
        #bc3 = first_candle['close'] < first_candle['vwma']
        bc3 = first_candle['pma_slope'] > 0
        #bc4 = first_candle['rsi'] > 20
        #bc5 = second_candle['volume'] > 500
        #bc5 = second_candle['volume'] > 50000
        bc6 = traded == "no"
        print("BUY ", current_time, bc2, bc3, bc6)

        if bc2 and bc3 and bc6:
#        if bc1 and bc2 and bc3 and bc4 and bc5 and bc6:
          for expiry in expiry:  
            print("Buy Signal Formed")
            ce_name, pe_name, strike = tsl.ATM_Strike_Selection(Underlying= symbol, Expiry= expiry)                                                                
            lot_size = tsl.get_lot_size(ce_name) * 5
            entry_orderid = tsl.order_placement(ce_name, 'NFO', lot_size, 0, 0, 'MARKET', 'BUY', 'MIS')
            traded = "yes"
            print(ce_name, pe_name, strike, lot_size, entry_orderid, trade_info)  

            # Ensure sl is stored as a float
            trade_info['options_name'] = pe_name, ce_name
            trade_info['qty'] = lot_size
#            TRAIL_PCT = 0.02
 #           trade_info['highest_price'] = max(trade_info['highest_price'], index_ltp)
#            trailing_sl = trade_info['highest_price'] * (1 - TRAIL_PCT) # Convert to float
#            trade_info['trailing_sl'] = trailing_sl
            trade_info['CE_PE'] = "PE", "CE"
    #        trade_info['symbol'] = symbol  # Store the traded symbol

        # ---------- EXIT CHECK (only for the traded symbol) ----------
        if traded == "yes":
            # Get fresh data for the traded symbol only
            exit_chart = tsl.get_historical_data(tradingsymbol=symbol, exchange='INDEX', timeframe="1")
#           exit_chart['rsi'] = talib.RSI(exit_chart['close'], timeperiod=14)
            exit_chart.set_index(pd.DatetimeIndex(exit_chart['timestamp']), inplace=True)
#            typical_price = (exit_chart['high'] + exit_chart['low'] + exit_chart['close']) / 3
#           exit_chart['vwap'] = (typical_price * exit_chart['volume']).cumsum() / exit_chart['volume'].cumsum()
#           supertrend_df = ta.supertrend(exit_chart['high'], exit_chart['low'], exit_chart['close'], length=10, multiplier=2.0)
#           exit_chart = pd.concat([exit_chart, supertrend_df], axis=1, join='inner')
            exit_chart['pma'] = exit_chart['close'].rolling(window=10).mean()
            exit_chart['pma_slope'] = exit_chart['pma'].diff()
            current_candle = exit_chart.iloc[-1]

            # Get current LTP of the option
#            ltp_data = tsl.get_ltp_data(names=[trade_info['options_name']])
#            index_ltp = float(ltp_data[trade_info['options_name']])  # Extract float value

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

            close = float(current_candle['close'])
            pma = float(current_candle['pma'])
            slope = float(current_candle['pma_slope'])

            if long_position:
                cond1 = close < pma          # price lost strength
                cond2 = slope < 0            # trend slope reversed

                if cond1 and cond2:
                    exit_flag = True
                    remark = "Trend Reversal to DOWN"

                elif short_position:

                    cond1 = close > pma          # price gained strength
                    cond2 = slope > 0            # trend slope reversed

                    if cond1 and cond2:
                        exit_flag = True
                        remark = "Trend Reversal to UP"

                if exit_flag:
                    print(f"EXIT TRIGGERED: {remark}")

                    exit_orderid = tsl.order_placement(trade_info['options_name'],'NFO',trade_info['qty'],0,0,'MARKET','SELL','MIS')
                    traded = "no"
                    trade_info = {}



                    log_data = pd.DataFrame([{
                        "timestamp": datetime.datetime.now(),
                        "symbol": trade_info['symbol'],
                        "options_name": trade_info['options_name'],
                        "qty": trade_info['qty'],
                        "ltp": index_ltp,
 #                       "trailing_sl": trade_info['trailing_sl'],
                        "CE_PE": trade_info['CE_PE'],
                        "order_id": exit_orderid,
                        "remark": remark
                    }])
                    log_data.to_csv("trade_log.csv", mode="a", header=not pd.io.common.file_exists("trade_log.csv"), index=False)

                    # Reset trade flag after exit
                    traded = "no"
                    trade_info = {"options_name": None, "qty": None, "CE_PE": None, "symbol": None}

order_id is returning as none

Hi @dattaswaami ,

The order_id is returning as None because MARKET orders are not supported by the API. In such cases, a market protection parameter is required.

As an alternative, you can use a LIMIT order with a price close to the current market price, which will effectively act like a MARKET order .

Refer the link to place orders -

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 pta
import pandas_ta as ta
import warnings

warnings.filterwarnings("ignore")

# --------------- for dhan login ----------------
CLIENT_CODE = ""
ACCESS_TOKEN = " "

tsl = Tradehull(CLIENT_CODE, ACCESS_TOKEN)

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

while True:
    
        time.sleep(2)

        current_time = datetime.datetime.now()

        index_chart = tsl.get_historical_data(
            tradingsymbol='NIFTY MAY FUT',
            exchange='NFO',
            timeframe="5"
        )
        # option_chain = tsl.get_option_chain(Underlying="NIFTY", exchange="INDEX", expiry=1, num_strikes=10)
        # option_chain = pd.DataFrame(option_chain)
        # print(option_chain.head())


        #df= pd.read_csv("nifty_option_chain.csv")

        # ------------------------ apply indicators ------------------------

        index_chart['rsi'] = talib.RSI(index_chart['close'], timeperiod=14)
 
        supertrend_df = ta.supertrend(index_chart['high'], index_chart['low'], index_chart['close'], length=10, multiplier=3.0)
        index_chart = index_chart.join(supertrend_df[['SUPERT_10_3.0']])

        #Bollinger Bands
        #index_chart["bb"] = talib.BBANDS(index_chart["close"], timeperiod=20, nbdevup=2, nbdevdn=2, matype=0)


        # EMA 20-period
        index_chart['ema20'] = talib.EMA(index_chart["close"] , timeperiod=20, )

        # EMA 50-period
        index_chart['ema50'] = talib.EMA(index_chart["close"] , timeperiod=50, )

        # EMA 200-period
        #index_chart['ema200'] = talib.EMA(index_chart["close"] , timeperiod=200, )

        #ADX 
        index_chart['adx'] = adx = talib.ADX(index_chart["high"], index_chart["low"], index_chart["close"], timeperiod=14)

        #atr
        index_chart["atr"]= talib.ATR(index_chart["high"], index_chart["low"], index_chart["close"], timeperiod=14)

        #20 days avg volume
        index_chart['avg_volume_20'] = index_chart['volume'].rolling(window=20).mean()

        #PCR
        #call_oi = option_chain['ce_oi'].sum()
        #put_oi  = option_chain['pe_oi'].sum()
        #pcr = put_oi / call_oi 

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

        # ---------------------------- SELL ENTRY CONDITIONS ----------------------------
        bc1 = running_candle['close'] > running_candle['ema20'] and running_candle['close'] > running_candle['ema50']  
        bc2 =  40 < running_candle['rsi'] < 70
        #bc3 = running_candle['volume'] > running_candle['avg_volume_20']
        #bc4 = running_candle['SUPERT_10_3.0'] == 1
        bc5 = running_candle['adx'] > 25
        #bc6 = pcr < 0.7
        print(f"Buy Conditions: {bc1}, {bc2},  {bc5}")

        sc1 = running_candle['close'] < running_candle['ema20'] and running_candle['close'] < running_candle['ema50']  
        sc2 = 30 < running_candle['rsi'] < 60
        #sc3 = running_candle['volume'] > running_candle['avg_volume_20']
        #sc4 = running_candle['SUPERT_10_3.0'] == -1
        sc5 = running_candle['adx'] > 25
        #sc6 = pcr > 1.3
        print(f"Sell Conditions: {sc1}, {sc2},  {sc5}")


        if sc1 and sc2 and sc5 and traded == "no":
            print("Sell Signal Formed")

            ce_name, pe_name, strike = tsl.ATM_Strike_Selection(
                Underlying='NIFTY',
                Expiry='1'
            )

            lot_size = tsl.get_lot_size(pe_name) * 5

            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']
            trade_info['CE_PE'] = "PE"
        elif bc1 and bc2 and bc5 and traded == "no":
            print("Buy Signal Formed")

            ce_name, pe_name, strike = tsl.ATM_Strike_Selection(
                Underlying='NIFTY  ',
                Expiry='1'
            )

            lot_size = tsl.get_lot_size(ce_name) * 5

            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']
            trade_info['CE_PE'] = "CE"

       # ---------------------------- EXIT MANAGEMENT ----------------------------
        if traded == "yes":

            opt_price = tsl.get_ltp_data(names=[trade_info['options_name']])[trade_info['options_name']]

            side = trade_info['CE_PE']
            lot_size = trade_info['qty']
            slippage = 0.01
            brokerage = 40

            atr = index_chart['atr'].iloc[-1] if 'atr' in index_chart.columns else 10  # fallback

    # ---------------- CE LOGIC ----------------
            if side == "CE":
                entry_price = trade_info.get('entry_price')

        # trailing SL
                new_sl = entry_price - 1.5 * atr
                trade_info['sl'] = max(trade_info['sl'], new_sl)

                risk = abs(entry_price - trade_info['sl'])
                target = entry_price + 2 * risk

                sl_hit = opt_price <= trade_info['sl']
                tg_hit = opt_price >= target

                print(f"CE SL: {trade_info['sl']}, TARGET: {target}, LTP: {opt_price}")

    # ---------------- PE LOGIC ----------------
            elif side == "PE":
                entry_price = trade_info.get('entry_price')

                new_sl = entry_price - 1.5 * atr
                trade_info['sl'] = max(trade_info['sl'], new_sl)

                risk = abs(entry_price - trade_info['sl'])
                target = entry_price + 2 * risk

                sl_hit = opt_price <= trade_info['sl']
                tg_hit = opt_price >= target

                print(f"PE SL: {trade_info['sl']}, TARGET: {target}, LTP: {opt_price}")

    # ---------------- EXIT ----------------
            if sl_hit or tg_hit:
                exit_price = opt_price * (1 - slippage)

                tsl.order_placement(
            trade_info['options_name'],
            'NFO',
            lot_size,
            0,
            0,
            'MARKET',
            'SELL',
            'MIS'
        )

                pnl = (exit_price - entry_price) * lot_size - brokerage

                print(f"EXIT {side} @ {exit_price}")
                print(f"PnL: {pnl}")

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

Codebase Version 3.2.1

Attempting authentication using ACCESS TOKEN.

reading existing file all_instrument 2026-04-30.csv

Already logged in for today, so reusing the token

Instrument file retrieved successfully

-----SUCCESSFULLY LOGGED INTO DHAN-----

Buy Conditions: True, True, True

Sell Conditions: False, False, True

Buy Signal Formed

Exception at getting Expiry list as Check the Tradingsymbol

Unable to find the correct Expiry for NIFTY

Traceback (most recent call last):

File “c:\Users\Admin\Desktop\NEW STRATEGY\POSITIONAl OPTIONS live.PY”, line 121, in

ce_name, pe_name, strike = tsl.ATM_Strike_Selection(

^^^^^^^^^^^^^^^^^^^^^^^^

TypeError: cannot unpack non-iterable NoneType object

Please can you help me with this too?

Hi @dattaswaami
this issue is in ATM strike selection… where the expiry shall be given in int, but it was given in str

ce_name, pe_name, strike = tsl.ATM_Strike_Selection(Underlying='NIFTY',Expiry='1') # wrong '1'
ce_name, pe_name, strike = tsl.ATM_Strike_Selection(Underlying='NIFTY',Expiry=1) # right 1