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