Hi @Tradehull_Imran sir need your help
The algo is working fine, but whenever a position exits, the algo is buying the same position again if the conditions are met. I want it to only buy the position the second time if it is 50+ on the CE/PE side. Can you please help me with the code?
could you please provide me code if possible .
this is the error what i am getting it.
traded = “no”
trade_info = {“options_name”: None, “qty”: None, “sl”: None, “CE_PE”: None, “entry_price”: None}
used_strikes = set() # Set to track used strikes for CE and PE
Flag to track if algo has been logged in for the day
algo_logged_in_today = False
Define a cache for LTP and a timestamp to store the last time it was updated
ltp_cache = {}
ltp_timestamp = {}
def fetch_ltp_with_rate_limit(symbol):
global ltp_cache, ltp_timestamp
current_time = time.time()
# Check if LTP is already cached and if it's recent (cache for 30 seconds)
if symbol in ltp_cache and (current_time - ltp_timestamp[symbol]) < 30:
return ltp_cache[symbol]
try:
# Fetch LTP from the API
ltp_data = tsl.get_ltp_data(names=[symbol])
if ltp_data and symbol in ltp_data:
ltp_value = ltp_data[symbol]
# Cache the LTP and timestamp it
ltp_cache[symbol] = ltp_value
ltp_timestamp[symbol] = current_time
return ltp_value
else:
print("Failed to fetch LTP for symbol:", symbol)
return None
except Exception as e:
print(f"Error fetching LTP for {symbol}: {e}")
return None
while True:
time.sleep(2)
try:
current_time = datetime.datetime.now()
current_time_str = current_time.strftime(“%H:%M”)
# Check if the algorithm is logged in before 9:15 AM
if current_time_str < "09:15" and not algo_logged_in_today:
print("Algo logged in before 9:15 AM. It will automatically activate at 9:15 AM.")
continue
# Market opening condition at 9:15 AM
if current_time_str == "09:15" and not algo_logged_in_today:
print("Algo is now active. Starting trading at 9:15 AM.")
algo_logged_in_today = True
# Stop trading at 3:20 PM and exit the algorithm at 3:30 PM
if current_time_str == "15:20":
print("Market closing. Selling all positions...")
if traded == "yes":
tsl.order_placement(
trade_info['options_name'], 'NFO', trade_info['qty'], 0, 0, 'MARKET', 'SELL', 'MIS'
)
traded = "no"
continue
elif current_time_str == "15:30":
print("Market is closed. Algorithm stopping.")
break
# Fetch index chart data
index_chart = tsl.get_historical_data(tradingsymbol="NIFTY JAN FUT", exchange="NFO", timeframe="5")
if index_chart.empty:
print("No data retrieved from API. Retrying...")
continue
# Apply indicators
index_chart['SMA'] = talib.SMA(index_chart['close'], timeperiod=5)
index_chart['RSI'] = talib.RSI(index_chart['close'], timeperiod=14)
supertrend = ta.supertrend(index_chart['high'], index_chart['low'], index_chart['close'], length=10, multiplier=2)
index_chart = pd.concat([index_chart, supertrend], axis=1, join="inner")
# Extract candles
first_candle = index_chart.iloc[-3]
second_candle = index_chart.iloc[-2]
running_candle = index_chart.iloc[-1]
# Define conditions for PE buying
pe_conditions = (
running_candle['RSI'] < 80,
running_candle['close'] < running_candle['SMA'],
running_candle['volume'] > second_candle['volume'],
running_candle['close'] < running_candle['SUPERT_10_2.0'],
running_candle['volume'] > 50000
)
# Define conditions for CE buying
ce_conditions = (
running_candle['RSI'] > 20,
running_candle['close'] > running_candle['SMA'],
running_candle['volume'] > second_candle['volume'],
running_candle['close'] > running_candle['SUPERT_10_2.0'],
running_candle['volume'] > 50000
)
# Place PE order
if all(pe_conditions) and traded == "no":
ce_name, pe_name, strike = tsl.ATM_Strike_Selection(Underlying='NIFTY', Expiry='30-01-2025')
while pe_name in used_strikes:
strike -= 50
ce_name, pe_name, _ = tsl.ATM_Strike_Selection(Underlying='NIFTY', Expiry='30-01-2025', strike_override=strike)
print(f"Placing PE order for {pe_name}.")
# Order placement logic here
used_strikes.add(pe_name)
# Place CE order
if all(ce_conditions) and traded == "no":
ce_name, pe_name, strike = tsl.ATM_Strike_Selection(Underlying='NIFTY', Expiry='30-01-2025')
while ce_name in used_strikes:
strike += 50
ce_name, pe_name, _ = tsl.ATM_Strike_Selection(Underlying='NIFTY', Expiry='30-01-2025', strike_override=strike)
print(f"Placing CE order for {ce_name}.")
# Order placement logic here
used_strikes.add(ce_name)
except Exception as e:
print(f"Error occurred: {e}")
traceback.print_exc()