Issues with closing out a trade
-
Hi Everyone
Please kindly look into this code and advise me, how to handle the ```
self.order = self.close()''' properly. When the a trade gets created I am able to insert the records properly for both Buy and Sell.But when the Close happens, I want to create a counter record like for e.g if I am trying to close a Buy trade then a record needs to created saying "Exit Long". But in my current code logic the Buy trades are being closed as "Enter Short" and Sell trades are being closed as "Enter Long"
def notify_order(self, order): if order.status in [order.Submitted, order.Accepted]: # Buy/Sell order submitted/accepted to/by broker - Nothing to do return # Check if an order has been completed # Attention: broker could reject order if not enough cash if order.status in [order.Completed]: #print(order.status) if order.isbuy(): self.con.execute( "insert into results(Symbol,Trade_Exe_Date,Trade_Type,Action,Price,Added_On) values(?,?,?,?,?,?)", (self.stock, str(self.datas[0].datetime.date(0)), "Enter Long", "Buy", round(order.executed.price,2), str(dt.datetime.today()))) self.con.commit() elif order.issell(): # Sell #self.exec_price = round(order.executed.price, 2) self.con.execute( "insert into results(Symbol,Trade_Exe_Date,Trade_Type,Action,Price,Added_On) values(?,?,?,?,?,?)", (self.stock, str(self.datas[0].datetime.date(0)), "Enter Short", "Sell", round(order.executed.price,2), str(dt.datetime.today()))) self.con.commit() self.bar_executed = len(self) elif order.status in [order.Canceled, order.Margin, order.Rejected]: self.log('Order Canceled/Margin/Rejected') self.order = None def notify_trade(self, trade): if not trade.isclosed: return self.con.execute("insert into results(Symbol,Trade_Exe_Date,Trade_Type,Action,Price,Profit,Added_On) values(?,?,?,?,?,?,?)", (self.stock, str(self.datas[0].datetime.date(0)), "Enter Short", "Sell", self.exec_price,round(trade.pnl,2), str(dt.datetime.today()))) self.con.commit() def next(self): if self.order: return # Check if we are in the market for d in self.getdatanames(): pos = self.getpositionbyname(d).size if pos == 0: if #condition self.order = self.buy() elif #condition self.order = self.sell() else: if pos > 0: if #condition self.order = self.close() else: if #condition self.order = self.close()
('^NSEI', '2021-09-24', 'Enter Long', 'Buy', 17638.89, None, '2023-09-01 17:32:40.664286') ('^NSEI', '2021-10-04', 'Enter Short', 'Sell', 17612.46, None, '2023-09-01 17:32:40.781271')
And also in the place of the second row, for instead of "None" I need to insert or update the
trade.pnl
value. If any one can help me how to achieve this that would be great. I am having hard time identifying how to do my logic when the trade is getting closed. I am fine with trade opening part.