Backtrader Community

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

    Capturing the P&L for the closed trade

    General Code/Help
    1
    1
    11
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • S
      sat7134 last edited by

      Hi All

      The below code works as expeceted, whenever there is a buy or sell then the record gets successfully inserted in the DB.

          if order.status in [order.Completed]:
              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", order.executed.price,str(dt.datetime.today())))
                  # self.con.commit()
                  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.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()
      

      But when I tried to update the P&L as below, the P&L for the last trade is getting updated for all the trades. I want the P&L to be attached to the closed trade that corresponds to the Opened trade. Can someone please help me how to achieve this?

      def notify_trade(self, trade):
          if not trade.isclosed:
              return
      
          elif trade.isclosed:
          #self.con.execute("update results set Profit = ? where Symbol = ?",(trade.pnl, self.stock))
          #self.con.commit()
      
      1 Reply Last reply Reply Quote 0
      • 1 / 1
      • First post
        Last post
      Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors