@Tradehull_Imran,
Sir
Now code is working as expected, logged in and logout as per time mentioned it has Placed the order but against one buy order there are multiple sell orders. is this ok.
Hi @Tradehull_Imran sir,
Can you please share the dhan codebase for reference which was available on notion.so?
simple yet powerfull,
OPTION SELLING
USE VWAP INDICATOR,
TIME FRAME - 5MIN
INSTRUMENT - ATM STRADDLE STRIKE COMBINED PRICE
AS AND WHEN ITS COMES DOWN VWAP SELL THE STRADDLE
RR WILL BE 1:2
its working fine now… it seems there was problem with ITC symbol yesterday.
When we fetching the OHLC chart data for each instrument in a separate API call , we are hitting the Data API rate limits. As Dhan support to fetch OHLC data of 1000 instruments in a single API, refer this link Market Quote - DhanHQ Ver 2.0 / API Document . please update the get_historic_data() to fetch chart data for the list of trading symbols instead of 1 instrument in a one API call. And consider the same for LTP fetch function. With this I think we can avoid the rate limit issues to some extend. Looking forward for your inputs and support…
Hello @Tradehull_Imran , everyone
Equity backtesting —
Mothercandle strategy with Volume BO
Time Frame 15 min
Indicators - Volume, RSI >60
Screener that scans Mothercandle structure after 3rd completed candle.
Watchlist to have stocks 3-5 based on screener results
Rule :
Strategy to begin at 10 am
the first candle of the day = Mothercandle that should be about 1-3 % in size
the subsequent 2nd and 3rd should be child candle
the candle that gives BO or BD should have 2x volume > Mothercandle and RSI>60
SL - Low of Mothecandle about 2%
TSL - 1%
Risk Reward 1:2
Suggestion welcome
Thanks
Yeah. Have deleted the existing token and created a new one & its working.
However, Its better to find out why it didn’t work for the previous token to avoid same issue in future
Getting Exception for instrument name BANKNIFTY-JAN2025-49900-CE as Check the Tradingsymbol got exception in pnl as 'BANKNIFTY-Jan2025-49900-CE'
kindly check
Folks anyone from Bangalore here?
We are coming to your city - exclusively for an Algo Trading Workshop!
Date: 11th January, Saturday
Time: 10 AM onwards
Here’s the link for registration link:
We look forward to seeing you soon!
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 ta
import xlwings as xw
import winsound
client_code = “1102790337”
token_id = “eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJkaGFuIiwicGFydG5lcklkIjoiIiwiZXhwIjoxNzM2ODYwMTMxLCJ0b2tlbkNvbnN1bWVyVHlwZSI6IlNFTEYiLCJ3ZWJob29rVXJsIjoiIiwiZGhhbkNsaWVudElkIjoiMTEwMjc5MDMzNyJ9.Leop6waGeVfmBOtczNEcjRWmC8pUGWQf54YPINGDi_PZjk1IvW-DDdaYXsgM_s8McOT44q4MjEQxGXU0lduK0A”
tsl = Tradehull(client_code,token_id)
watchlist = [‘BEL’, ‘BOSCHLTD’, ‘COLPAL’, ‘HCLTECH’, ‘HDFCBANK’, ‘HAVELLS’, ‘HAL’, ‘ITC’, ‘IRCTC’, ‘INFY’, ‘LTIM’, ‘MARICO’, ‘MARUTI’, ‘NESTLEIND’, ‘PIDILITIND’, ‘TCS’, ‘TECHM’, ‘WIPRO’]
single_order = {‘name’:None, ‘date’:None , ‘entry_time’: None, ‘entry_price’: None, ‘buy_sell’: None, ‘qty’: None, ‘sl’: None, ‘exit_time’: None, ‘exit_price’: None, ‘pnl’: None, ‘remark’: None, ‘traded’:None}
orderbook = {}
wb = xw.Book(‘Live Trade Data.xlsx’)
live_Trading = wb.sheets[‘Live_Trading’]
completed_orders_sheet = wb.sheets[‘completed_orders’]
reentry = “yes” #“yes/no”
completed_orders =
bot_token = “8059847390:AAECSnQK-yOaGJ-clJchb1cx8CDhx2VQq-M”
receiver_chat_id = “1918451082”
live_Trading.range(“A2:Z100”).value = None
completed_orders_sheet.range(“A2:Z100”).value = None
for name in watchlist:
orderbook[name] = single_order.copy()
while True:
print("starting while Loop \n\n")
current_time = datetime.datetime.now().time()
if current_time < datetime.time(13, 55):
print(f"Wait for market to start", current_time)
time.sleep(1)
continue
if current_time > datetime.time(15, 15):
order_details = tsl.cancel_all_orders()
print(f"Market over Closing all trades !! Bye Bye See you Tomorrow", current_time)
pdb.set_trace()
break
all_ltp = tsl.get_ltp_data(names = watchlist)
for name in watchlist:
orderbook_df = pd.DataFrame(orderbook).T
live_Trading.range('A1').value = orderbook_df
completed_orders_df = pd.DataFrame(completed_orders)
completed_orders_sheet.range('A1').value = completed_orders_df
current_time = datetime.datetime.now()
print(f"Scanning {name} {current_time}")
try:
chart = tsl.get_historical_data(tradingsymbol = name,exchange = 'NSE',timeframe="5")
chart['rsi'] = talib.RSI(chart['close'], timeperiod=14)
cc = chart.iloc[-2]
# buy entry conditions
bc1 = cc['rsi'] > 45
bc2 = orderbook[name]['traded'] is None
except Exception as e:
print(e)
continue
if bc1 and bc2:
print("buy ", name, "\t")
margin_avialable = tsl.get_balance()
margin_required = cc['close']/4.5
if margin_avialable < margin_required:
print(f"Less margin, not taking order : margin_avialable is {margin_avialable} and margin_required is {margin_required} for {name}")
continue
orderbook[name]['name'] = name
orderbook[name]['date'] = str(current_time.date())
orderbook[name]['entry_time'] = str(current_time.time())[:8]
orderbook[name]['buy_sell'] = "BUY"
orderbook[name]['qty'] = 1
try:
entry_orderid = tsl.order_placement(tradingsymbol=name ,exchange='NSE', quantity=orderbook[name]['qty'], price=0, trigger_price=0, order_type='MARKET', transaction_type='BUY', trade_type='MIS')
orderbook[name]['entry_orderid'] = entry_orderid
orderbook[name]['entry_price'] = tsl.get_executed_price(orderid=orderbook[name]['entry_orderid'])
orderbook[name]['tg'] = round(orderbook[name]['entry_price']*1.002, 1) # 1.01
orderbook[name]['sl'] = round(orderbook[name]['entry_price']*0.998, 1) # 99
sl_orderid = tsl.order_placement(tradingsymbol=name ,exchange='NSE', quantity=orderbook[name]['qty'], price=0, trigger_price=orderbook[name]['sl'], order_type='STOPMARKET', transaction_type ='SELL', trade_type='MIS')
orderbook[name]['sl_orderid'] = sl_orderid
orderbook[name]['traded'] = "yes"
message = "\n".join(f"'{key}': {repr(value)}" for key, value in orderbook[name].items())
message = f"Entry_done {name} \n\n {message}"
tsl.send_telegram_alert(message=message,receiver_chat_id=receiver_chat_id,bot_token=bot_token)
except Exception as e:
print(e)
pdb.set_trace(header= "error in entry order")
if orderbook[name]['traded'] == "yes":
bought = orderbook[name]['buy_sell'] == "BUY"
if bought:
try:
ltp = all_ltp[name]
sl_hit = tsl.get_order_status(orderid=orderbook[name]['sl_orderid']) == "TRADED"
tg_hit = ltp > orderbook[name]['tg']
except Exception as e:
print(e)
pdb.set_trace(header = "error in sl order cheking")
if sl_hit:
try:
orderbook[name]['exit_time'] = str(current_time.time())[:8]
orderbook[name]['exit_price'] = tsl.get_executed_price(orderid=orderbook[name]['sl_orderid'])
orderbook[name]['pnl'] = round((orderbook[name]['exit_price'] - orderbook[name]['entry_price'])*orderbook[name]['qty'],1)
orderbook[name]['remark'] = "Bought_SL_hit"
message = "\n".join(f"'{key}': {repr(value)}" for key, value in orderbook[name].items())
message = f"SL_HIT {name} \n\n {message}"
tsl.send_telegram_alert(message=message,receiver_chat_id=receiver_chat_id,bot_token=bot_token)
if reentry == "yes":
completed_orders.append(orderbook[name])
orderbook[name] = None
except Exception as e:
print(e)
pdb.set_trace(header = "error in sl_hit")
if tg_hit:
try:
tsl.cancel_order(OrderID=orderbook[name]['sl_orderid'])
time.sleep(2)
square_off_buy_order = tsl.order_placement(tradingsymbol=orderbook[name]['name'] ,exchange='NSE', quantity=orderbook[name]['qty'], price=0, trigger_price=0, order_type='MARKET', transaction_type='SELL', trade_type='MIS')
orderbook[name]['exit_time'] = str(current_time.time())[:8]
orderbook[name]['exit_price'] = tsl.get_executed_price(orderid=square_off_buy_order)
orderbook[name]['pnl'] = (orderbook[name]['exit_price'] - orderbook[name]['entry_price'])*orderbook[name]['qty']
orderbook[name]['remark'] = "Bought_TG_hit"
message = "\n".join(f"'{key}': {repr(value)}" for key, value in orderbook[name].items())
message = f"TG_HIT {name} \n\n {message}"
tsl.send_telegram_alert(message=message,receiver_chat_id=receiver_chat_id,bot_token=bot_token)
if reentry == "yes":
completed_orders.append(orderbook[name])
orderbook[name] = None
winsound.Beep(1500, 10000)
except Exception as e:
print(e)
pdb.set_trace(header = "error in tg_hit")
Hi, @Tradehull_Imran sir, I have tried my level best to make a alog with the help of API Trades Meetup&Workshop
files, Please check it from your end , Sir, because Squareoff Order is not placing when tg_hit = ltp > orderbook[name]['tg']
Got it sir
Thank you!!!
YEP
Yes I also have the same opinion of getting OHLC data of 1000 instruments in a single API, we expect from Tradehull team to suggest a solution. As far as LTP is concerned, if you are using LTP in a loop where you are also fetching OHCL then instead of LTP you can use close of current candle as LTP “LTP=chart[‘close’].iloc[-1]” along with a considerable value of time interval in time.sleep(t). I think it will minimize API issue.
@Tradehull_Imran how to place bracket orders?, entry, stop loss and target together?
is this right?
tsl.order_placement(
tradingsymbol = stock_name,
exchange = “NSE”,
quantity = qty,
price = entry_price
trigger_price = entry_price,
order_type = “LIMIT”,
transaction_type = “BUY”,
trade_type = “MIS”,
validity =‘DAY’,
bo_profit_value = target,
bo_stop_loss_Value = stop_loss
)
@Tradehull_Imran Sir
me too getting the error
Exception for instrument name NIFTY-JAN2025-23750-CE as Check the Tradingsymbol
got exception in pnl as ‘NIFTY-Jan2025-23750-CE’
Algo is working 11:47:06.280986
BUY 11:47:06.280986 True True True False True True False first_candle 11:35:00
SELL 11:47:06.280986 False False False True False True True first_candle 11:35:00
Exception for instrument name NIFTY-JAN2025-23750-CE as Check the Tradingsymbol
got exception in pnl as ‘NIFTY-Jan2025-23750-CE’
Algo is working 11:47:17.886375
@Tradehull_Imran
Since we already have a two-candle strategy in place and it’s proven to be effective, why not start backtesting with the same? Instead of reinventing the wheel, we can focus our energy on optimizing and fine-tuning the existing strategy to achieve even better results.
Let’s leverage what’s already working and build upon it for greater efficiency and success.
@RahulDeshpande Ji
Thank you so much for considering us Bangaloreans and organizing a workshop here—it means a lot! I’ve already registered and am now eagerly waiting for approval.
Looking forward to the opportunity to learn and engage during the workshop.
Very Good Morning Sir.
Info is from ‘Backtrader’ : Hello Algotrading!
A classic Simple Moving Average Crossover strategy, can be easily implemented and in different ways. The results and the chart are the same for the three snippets presented below.
- Buy/Sell Code Snippet
- Target Orders Code Snippet
- Signals Code Snippet
Buy/Signal Code: `from datetime import datetime
import backtrader as bt
Create a subclass of Strategy to define the indicators and logic
class SmaCross(bt.Strategy):
# list of parameters which are configurable for the strategy
params = dict(
pfast=10, # period for the fast moving average
pslow=30 # period for the slow moving average
)
def __init__(self):
sma1 = bt.ind.SMA(period=self.p.pfast) # fast moving average
sma2 = bt.ind.SMA(period=self.p.pslow) # slow moving average
self.crossover = bt.ind.CrossOver(sma1, sma2) # crossover signal
def next(self):
if not self.position: # not in the market
if self.crossover > 0: # if fast crosses slow to the upside
self.buy() # enter long
elif self.crossover < 0: # in the market & cross to the downside
self.close() # close long position
cerebro = bt.Cerebro() # create a “Cerebro” engine instance
Create a data feed
data = bt.feeds.YahooFinanceData(dataname=‘MSFT’,
fromdate=datetime(2011, 1, 1),
todate=datetime(2012, 12, 31))
cerebro.adddata(data) # Add the data feed
cerebro.addstrategy(SmaCross) # Add the trading strategy
cerebro.run() # run it all
cerebro.plot() # and plot it with a single command`
Target Orders Code: `from datetime import datetime
import backtrader as bt
Create a subclass of Strategy to define the indicators and logic
class SmaCross(bt.Strategy):
# list of parameters which are configurable for the strategy
params = dict(
pfast=10, # period for the fast moving average
pslow=30 # period for the slow moving average
)
def __init__(self):
sma1 = bt.ind.SMA(period=self.p.pfast) # fast moving average
sma2 = bt.ind.SMA(period=self.p.pslow) # slow moving average
self.crossover = bt.ind.CrossOver(sma1, sma2) # crossover signal
def next(self):
if not self.position: # not in the market
if self.crossover > 0: # if fast crosses slow to the upside
self.order_target_size(target=1) # enter long
elif self.crossover < 0: # in the market & cross to the downside
self.order_target_size(target=0) # close long position
cerebro = bt.Cerebro() # create a “Cerebro” engine instance
Create a data feed
data = bt.feeds.YahooFinanceData(dataname=‘MSFT’,
fromdate=datetime(2011, 1, 1),
todate=datetime(2012, 12, 31))
cerebro.adddata(data) # Add the data feed
cerebro.addstrategy(SmaCross) # Add the trading strategy
cerebro.run() # run it all
cerebro.plot() # and plot it with a single command`
Signals Code: `from datetime import datetime
import backtrader as bt
Create a subclass of SignaStrategy to define the indicators and signals
class SmaCross(bt.SignalStrategy):
# list of parameters which are configurable for the strategy
params = dict(
pfast=10, # period for the fast moving average
pslow=30 # period for the slow moving average
)
def __init__(self):
sma1 = bt.ind.SMA(period=self.p.pfast) # fast moving average
sma2 = bt.ind.SMA(period=self.p.pslow) # slow moving average
crossover = bt.ind.CrossOver(sma1, sma2) # crossover signal
self.signal_add(bt.SIGNAL_LONG, crossover) # use it as LONG signal
cerebro = bt.Cerebro() # create a “Cerebro” engine instance
Create a data feed
data = bt.feeds.YahooFinanceData(dataname=‘MSFT’,
fromdate=datetime(2011, 1, 1),
todate=datetime(2012, 12, 31))
cerebro.adddata(data) # Add the data feed
cerebro.addstrategy(SmaCross) # Add the trading strategy
cerebro.run() # run it all
cerebro.plot() # and plot it with a single command`
I don’t Know how far is it useful??
I have a simple strategy,
INDEX OPTION SELLING (Short Iron condor)
Rules
- find and buy 0.1 delta deep OTM (hedge)
- Find ATM strikes and calculate the price difference in CE & PE prices.
- if the price difference is more than 10%, wait
- if the price difference is less than 10%, sell ATM CE & ATM PE
- keep watch on both legs prices; if any of the two’s LTP gets double of other leg’s LTP, exit both legs
- re-entry (start again from point 2)
The only problem is with the strategy that if there is a sudden spike in the market, 1 leg price gets multiplied and other legs price doesn’t get reduced in the same ratio.
any suugestions are welcome