import time
import pandas as pd
from datetime import datetime, time as dtime
from Dhan_Tradehull import Tradehull
client_code = ""
token_id = ''
tsl = Tradehull(client_code, token_id)
# SYMBOL = "NIFTY 27 NOV 2025 FUT"
SYMBOL = "NIFTY DEC FUT"
CSV = r"C:\Tradehull_mentorship\Live Algo's_shubham\supertrend_5min_trades.csv"
def super_trend(df, p=5, m=1):
hl2 = (df['high'] + df['low']) / 2
tr = pd.concat([
abs(df['high'] - df['low']),
abs(df['high'] - df['close'].shift(1)),
abs(df['low'] - df['close'].shift(1))
], axis=1).max(axis=1)
atr = tr.rolling(p).mean()
up, dn = hl2 - m * atr, hl2 + m * atr
st = [0] * len(df)
for i in range(1, len(df)):
if df['close'].iloc[i - 1] > st[i - 1]:
st[i] = max(up.iloc[i], st[i - 1])
else:
st[i] = min(dn.iloc[i], st[i - 1])
return pd.Series(st, index=df.index)
def has_position():
pos = tsl.get_positions()
if not isinstance(pos, pd.DataFrame) or pos.empty:
return False
return not pos[(pos['tradingsymbol'] == SYMBOL) & (pos['product_type'] == 'MIS')].empty
def already_traded_today():
try:
df_log = pd.read_csv(CSV)
today = datetime.now().strftime("%Y-%m-%d")
return not df_log[df_log['entry_time'].str.startswith(today)].empty
except:
return False
print(" Auto-Signal Checker Started (9:20 AM – 3:20 PM)")
while True:
now = datetime.now()
current_time = now.time()
market_start = dtime(9, 20)
market_end = dtime(15, 20)
if current_time > market_end:
print(" Market hours over. Stopping.")
break
if current_time < market_start:
time.sleep(30)
continue
# if already_traded_today():
# print(" Already traded today. Waiting till EOD.")
# time.sleep(60)
# continue
if has_position():
print(" Already in position. Skipping.")
time.sleep(60)
continue
print(f"\n Checking signal at {now.strftime('%H:%M:%S')}...")
raw = tsl.get_historical_data('NIFTY', 'INDEX', '1')
if not (isinstance(raw, (pd.DataFrame, list)) and len(raw) > 0):
print(" No data received")
time.sleep(30)
continue
df = pd.DataFrame(raw) if isinstance(raw, list) else raw
if df.empty:
print(" Empty data")
time.sleep(30)
continue
df['datetime'] = pd.to_datetime(df['timestamp'])
df.set_index('datetime', inplace=True)
df = df[['open', 'high', 'low', 'close']].sort_index()
if len(df) > 1:
df = df.iloc[:-1] # drop incomplete candle
if len(df) < 12:
print(f" Not enough candles: {len(df)}")
time.sleep(30)
continue
df['st'] = super_trend(df)
pc, cc = df['close'].iloc[-2], df['close'].iloc[-1]
ps, cs = df['st'].iloc[-2], df['st'].iloc[-1]
signal = None
if pc <= ps and cc > cs:
signal = "BUY"
elif pc >= ps and cc < cs:
signal = "SELL"
if not signal:
print(f" No signal | Close: {cc:.2f}, ST: {cs:.2f}")
else:
print(f" Signal: {signal} | Close: {cc:.2f}, ST: {cs:.2f}")
lot = tsl.get_lot_size(SYMBOL)
if not isinstance(lot, int)or lot <= 0:
print(" Invalid lot size")
else:
oid = tsl.order_placement(SYMBOL, 'NFO', lot, 0, 0, 'MARKET', signal, 'MIS')
if oid:
pd.DataFrame([{
"order_id": oid,"symbol": SYMBOL,"signal": signal,"quantity": lot,"entry_time": now.strftime("%Y-%m-%d %H:%M:%S"),"exit_date": ""}]).to_csv(CSV, mode='a', header=not pd.io.common.file_exists(CSV), index=False)
print(f" {signal} {lot} {SYMBOL} placed!")
else:
print(" Order failed")
time.sleep(60)
ye systum agar mujhe F&O ke saare stocks pe karna chahteheto kesse kar sakte he
Hi @7350982949 ,
- The Supertrend calculation itself might be incorrect, so it’s best to cross-check the signals against a chart.
- If you want to use a 75-minute timeframe, fetch 1-minute data and resample it to 75-minute candles before applying Supertrend.
- To run the strategy on F&O stocks, first create a watchlist containing all the symbols you want to trade. Then simply loop through that watchlist and execute the strategy for each symbol.
# sample example on how to use loop over the watchlist.
watchlist = ["RELIANCE", "TCS"]
for symbol in watchlist:
print(f"Running strategy for {symbol}...")
data = get_historical_data(symbol)
signal = generate_supertrend_signal(data)
if signal:
place_order(symbol, signal)