Hi @Tradehull_Imran , Sir.
Upon your teaching and your guidance, I have Completed my Algo, I am getting small errors while exiting the Trade, sir.
Please go through the Algo , and help me , Sir…
My Algo is
import pdb
import time
import datetime
import traceback
from Dhan_Tradehull_V2 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")
#-----------------------------------------------------------------------------------
client_code = "11"
token_id = "11"
tsl = Tradehull(client_code,token_id)
#----------------------------------------------------------------------------------
available_balance = tsl.get_balance()
leveraged_margin = available_balance*5
max_trades = 20
per_trade_margin = (leveraged_margin/max_trades)
max_loss = available_balance * -0.09 # max loss of 9%
#-----------------------------------------------------------------------------------------
watchlist = ['GOLDPETAL DEC FUT', 'CRUDEOILM DEC FUT', 'SILVERMIC FEB FUT']
traded_wathclist = []
#-----------------------------------------------------------------------------------------------------
while True:
live_pnl = tsl.get_live_pnl()
current_time = datetime.datetime.now().time()
if current_time < datetime.time(9, 18):
print("Wait for market to start", current_time)
time.sleep(1)
continue
if (current_time > datetime.time(23, 15)) or (live_pnl < max_loss):
# I_want_to_trade_no_more = tsl.kill_switch('ON')
order_details = tsl.cancel_all_orders()
print("Market is over, Bye see you tomorrow", current_time)
break
for stock_name in watchlist:
time.sleep(2)
print(f"Scanning {stock_name}")
# Conditions that are on 1 minute timeframe -------------------------------------------
chart_1 = tsl.get_historical_data(tradingsymbol=stock_name, exchange='MCX', timeframe="1")
pervious_candle = chart_1.iloc[-2]
no_repeat_order = stock_name not in traded_wathclist
# rsi ------------------------ apply indicators--------------------------------------
# Buy when rsi crosses above 55 and sell when rsi crosses below 45
# Ensure chart_1 has sufficient rows
if len(chart_1) <= 15:
print(f"Not enough data for {stock_name}. Skipping.")
continue
# Calculate RSI and drop NaN values
chart_1['rsi'] = talib.RSI(chart_1['close'], timeperiod=14)
chart_1['prev_rsi'] = chart_1['rsi'].shift(1)
chart_1.dropna(subset=['rsi', 'prev_rsi'], inplace=True)
# Add crossover columns
chart_1['uptrend_cross'] = (chart_1['prev_rsi'] <= 55) & (chart_1['rsi'] > 55)
chart_1['downtrend_cross'] = (chart_1['prev_rsi'] >= 45) & (chart_1['rsi'] < 45)
# Ensure the columns exist in the completed candle
cc_1 = chart_1.iloc[-2] # Second-to-last row
if 'uptrend_cross' not in cc_1 or 'downtrend_cross' not in cc_1:
print(f"Missing crossover columns for {stock_name}. Skipping.")
continue
# Access crossover values
uptrend_1 = cc_1['uptrend_cross']
downtrend_1 = cc_1['downtrend_cross']
print(f"Uptrend: {uptrend_1}, Downtrend: {downtrend_1}")
# Supertrend for Exit from open position -------------------------- apply indicators-----------------------------------
indi = ta.supertrend(chart_1['high'], chart_1['low'], chart_1['close'], 10, 1)
chart_1 = pd.concat([chart_1, indi], axis=1, join='inner')
cc_1 = chart_1.iloc[-2] #pandas completed candle of 1 min timeframe
exit_sell = cc_1['close'] > cc_1['SUPERT_10_1.0']
exit_buy = cc_1['close'] < cc_1['SUPERT_10_1.0']
# BUY conditions ------------------------------------------------------------------------------
breakout_b1 = ((pervious_candle['close'] - pervious_candle['open']) / pervious_candle['open']) * 100 # percentage change
breakout_b2 = pervious_candle['volume'] > 0.2 * chart_1['volume'].mean()
if uptrend_1 and breakout_b2 and (0.01 <= breakout_b1 <= 0.4) and no_repeat_order:
print(stock_name, "is in uptrend, Buy this script")
lot_size = tsl.get_lot_size(stock_name)
# Place buy order-------------------------------------------------------------------------
entry_orderid = tsl.order_placement(stock_name, 'MCX', lot_size, 0, 0, 'MARKET', 'BUY', 'MIS')
traded_wathclist.append(stock_name)
# SELL conditions -----------------------------------------------------------------------------
breakout_s1 = ((pervious_candle['close'] - pervious_candle['open']) / pervious_candle['open']) * 100 # percentage change
breakout_s2 = pervious_candle['volume'] > 0.2 * chart_1['volume'].mean()
if downtrend_1 and breakout_s2 and (-0.4 <= breakout_s1 <= -0.01) and no_repeat_order:
print(stock_name, "is in downtrend, Sell this script")
lot_size = tsl.get_lot_size(stock_name)
# Place sell order-------------------------------------------------------------------------
entry_orderid = tsl.order_placement(stock_name, 'MCX', lot_size, 0, 0, 'MARKET', 'SELL', 'MIS')
traded_wathclist.append(stock_name)
# Exit conditions based on Supertrend indicator----------------------------------------------------
for stock_name in traded_wathclist:
time.sleep(2)
print(f"Checking exit conditions for {stock_name}")
# Fetch updated 1-minute chart
chart_1 = tsl.get_historical_data(tradingsymbol=stock_name, exchange='MCX', timeframe="1")
# Apply Supertrend indicator again
indi = ta.supertrend(chart_1['high'], chart_1['low'], chart_1['close'], 10, 1)
chart_1 = pd.concat([chart_1, indi], axis=1, join='inner')
cc_1 = chart_1.iloc[-2] # Get the completed candle
# Exit conditions
exit_sell = cc_1['close'] > cc_1['SUPERT_10_1.0']
exit_buy = cc_1['close'] < cc_1['SUPERT_10_1.0']
# Check for existing positions to square off
position = tsl.get_position(stock_name) # Get current position details
if position['type'] == 'BUY' and exit_buy:
print(f"Exiting BUY position for {stock_name}")
exit_orderid = tsl.order_placement(stock_name, 'MCX', position['lot_size'], 0, 0, 'MARKET', 'SELL', 'MIS')
traded_wathclist.remove(stock_name)
elif position['type'] == 'SELL' and exit_sell:
print(f"Exiting SELL position for {stock_name}")
exit_orderid = tsl.order_placement(stock_name, 'MCX', position['lot_size'], 0, 0, 'MARKET', 'BUY', 'MIS')
traded_wathclist.remove(stock_name)
My error message is
GOLDPETAL DEC FUT is in uptrend, Buy this script
Checking exit conditions for GOLDPETAL DEC FUT
Traceback (most recent call last):
File "MCX - Exit.py", line 147, in <module>
position = tsl.get_position(stock_name) # Get current position details
AttributeError: 'Tradehull' object has no attribute 'get_position'