Announcement

Collapse

Looking for a User App or Add-On built by the NinjaTrader community?

Visit NinjaTrader EcoSystem and our free User App Share!

Have a question for the NinjaScript developer community? Open a new thread in our NinjaScript File Sharing Discussion Forum!
See more
See less

Partner 728x90

Collapse

PnL for last trade is always showing the result from the previous trade

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    PnL for last trade is always showing the result from the previous trade

    Hi

    I am trying to display the value of the PnL for the most recent trade

    Code:
    if (SystemPerformance.AllTrades.Count > 0){
    Trade lastTrade = SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count - 1];
    Draw.Text(this, @"rP"+CurrentBar, ""+lastTrade.ProfitCurrency, 0, Low[0]+5, Brushes.Yellow);
    Print("Last trade PnL: "+lastTrade.ProfitCurrency);
    }

    What happens is, if I have four trades, the first trade is ignored and the final three are labeled with text but the values on each correspond to the earlier draw event. So when it should output:
    Trade 1 - $10
    Trade 2 - $20
    Trade 3 - $10
    Trade 4 - $40

    instead I get:
    Trade 1 -
    Trade 2 - $10
    Trade 3 - $20
    Trade 4 - $10

    I tried using

    Code:
    Trade lastTrade = SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count];
    But then I get an out of range error for onbarupdate

    What am I doing wrong?

    #2
    Hello Smoky,

    Thanks for your post.

    I would suggest a slight modification to your code so that you are only printing or drawing text when the latest trade has closed instead of on each bar. Basically, it uses an int variable to hold the trades count and only allows your code to draw/print when a new trade occurs.

    At the class level I create a private int like: private int myTradeCount = 1;

    if (SystemPerformance.AllTrades.Count > 0 && myTradeCount != SystemPerformance.AllTrades.Count-1)
    {
    Trade lastTrade = SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count - 1];
    Draw.Text(this, @"rP"+CurrentBar, ""+lastTrade.ProfitCurrency, 0, Low[0]+5, Brushes.Yellow);
    Print(Time[0]+" Last trade PnL: "+lastTrade.ProfitCurrency);
    myTradeCount = SystemPerformance.AllTrades.Count -1;
    }


    I've attached a screenshot that shows several trades and you can follow the output window from the bottom up to the draw text on the chart from right to left. As you can see these are correct.

    Click image for larger version

Name:	Smoky-1.PNG
Views:	424
Size:	99.2 KB
ID:	1136512 ​​​​​​​
    Paul H.NinjaTrader Customer Service

    Comment


      #3
      I added your code but am getting exact same result. Everything is off by one place on the chart.

      This is the whole piece, separate drawing for a profit vs a loss (should have mentioned that but didn't want to over complicate the original question)

      Code:
      if (profit event occurs) {
      VerticalLine myLine = Draw.VerticalLine(this, "Profit"+CurrentBar, 0, true, "ProfitLine");
      if ((SystemPerformance.AllTrades.Count > 0) && (myTradeCount != SystemPerformance.AllTrades.Count-1)){
      Trade lastTrade = SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count - 1];
      Draw.Text(this, @"rP"+CurrentBar, ""+lastTrade.ProfitCurrency, 0, Low[0]+5, Brushes.Yellow);
      Print("Last trade PnL: "+lastTrade.ProfitCurrency);
      myTradeCount = SystemPerformance.AllTrades.Count -1;
      }}
      
      }if (loss event occurs) {
      VerticalLine myLine = Draw.VerticalLine(this, "Loss"+CurrentBar, 0, true, "LossLine");
      if ((SystemPerformance.AllTrades.Count > 0) && (myTradeCount != SystemPerformance.AllTrades.Count-1)){
      Trade lastTrade = SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count - 1];
      Draw.Text(this, @"rP"+CurrentBar, ""+lastTrade.ProfitCurrency, 0, Low[0]+5, Brushes.Yellow);
      Print("Last trade PnL: "+lastTrade.ProfitCurrency);
      myTradeCount = SystemPerformance.AllTrades.Count -1;
      }}
      Click image for larger version  Name:	2021-01-13_8-12-54.png Views:	0 Size:	348.1 KB ID:	1136518

      It is tough to see in the pic, but that "-29.499xxx" should be on the red line before it. Every profit/loss is off by one marker. That last green line on the chart is supposed to be the "133" profit. The next one before it should be "158". All of my lines are being drawn correctly (albeit one bar before the close, instead of one the close, as I intended, but I will make a new post about that later lol).
      Last edited by Smoky; 01-13-2021, 04:27 PM.

      Comment


        #4
        Hello Smoky,

        Thanks for your reply.

        The vertical lines are drawn when there is Unrealized PNL on the table.

        The trade count does not increase until the trade is finished. Therefore I would expect the drawText to show 1 bar after the vertical line appears and the text appears to be center above the bar where the exit occurred.


        Paul H.NinjaTrader Customer Service

        Comment


          #5
          The bars are intended to be drawn on the exit, and are being colored correctly with the exit's "profit" or "loss" per my table. But the prices that are drawn (separate code) are drawing the text on the wrong place. For some reason the bars are drawing a bar before the exit, but they do correspond to the correct exit.

          But that is a less important issue for now compared to getting the text to draw the correct profit-on-exit on the correct close. Perhaps these two issues are related, but I would rather make sure we solve the profit-on-exit text problem first.

          Thanks!

          Comment


            #6
            Hello Smoky,

            Thanks for your reply.

            Once the trade closes there is no more UnrealizedPNL so the condition to draw the vertical line cannot become true to draw the line on the bar where the exit occurs.

            I do not see the same thing as you. The print output trade sequence matches the chart and the chart matches the Trades performance table trade for trade. Nothing is shifted here.

            What version of NinjaTrader8 are you using (look under help about)?

            Are you testing in the strategy analyzer?

            Or are you applying to a chart with historical data and looking at the historical trades?

            Or are you showing actual live trades made?

            What is the calculate setting used on the strategy?



            Paul H.NinjaTrader Customer Service

            Comment


              #7
              First point: Unrealized PnL has nothing to do with this. I am only looking at actual, realized profit or loss on each trade.

              Second, do you see in my image, on the trades table, how the last trade is 133? Ok, so now look at the chart in my image, do you see the last trade marked there, it shows 158? Ok, now look back at the table. See the next trade up is 158? Ok... the chart is putting the 158 where the 133 should be. And every other price before that is also drawn on the wrong exit. The 133 is missing from the chart because it is in neverland or something.

              Ignore that the lines are being drawn a bar before the exit.... other than that they are correct. They show profit (green) and loss (red) where they should, and seem to sync with the table just fine. So, the lines are correct, so we can use those as a guide. Look down the chart you can see where there are red lines with profit and vice versa. That is wrong. The lines are correct, but the prices drawn are wrong.

              I am using NT 8.0.23.2 64-bit . I might add this to my sig lol

              I am applying a strategy to a chart and looking at realtime and historical data. I am not using the strategy analyzer.

              I've updated my code example above to be less confusing.
              Last edited by Smoky; 01-13-2021, 04:28 PM.

              Comment


                #8
                How about this... what is happening with the first four trades today?
                Click image for larger version

Name:	2021-01-13_17-15-11.png
Views:	282
Size:	458.1 KB
ID:	1136668
                Attached Files

                Comment


                  #9
                  Tried revising the code to simplify and feel like this should be doing what I want but instead I get the notorious Error on calling barUpdate

                  Code:
                  if (closing position event occurs){
                  if (myTradeCount != SystemPerformance.AllTrades.Count-1){
                  Trade lastTrade = SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count - 1];
                  if (lastTrade.ProfitCurrency > 0){VerticalLine myLine = Draw.VerticalLine(this, "Profit"+CurrentBar, 0, true, "ProfitLine");}
                  else if (lastTrade.ProfitCurrency < 0){VerticalLine myLine = Draw.VerticalLine(this, "Loss"+CurrentBar, 0, true, "LossLine");}
                  Draw.Text(this, @"rP"+CurrentBar, ""+lastTrade.ProfitCurrency, 0, Low[0]+5, Brushes.Yellow);
                  Print("Last trade PnL: "+lastTrade.ProfitCurrency);
                  myTradeCount = SystemPerformance.AllTrades.Count - 1;
                  }}
                  Last edited by Smoky; 01-13-2021, 09:14 PM.

                  Comment


                    #10
                    Hello Smoky,

                    Thanks for your reply.

                    From the previous code you posted, that looks like you have edited out now in post#3 it looks like the issue relates to the check for unrealized PNL. You have placed the trades code inside the If statement that checks for unrealized PNL.

                    Using the code I provided post#2, outside of the unrealized PNl check will produce all of the results.

                    Paul H.NinjaTrader Customer Service

                    Comment


                      #11
                      Ok let's try something else then. Ignore the rest of this discussion. Look at post #9 above only. Why is that code experiencing an error on calling barupdate? I don't get the error until bar 35, when a sell event occurs.

                      Comment


                        #12
                        Hello Smoky,

                        Thanks for your reply.

                        It looks like this line: if (myTradeCount != SystemPerformance.AllTrades.Count-1) is the likely culprit.

                        You would need to check that SystemPerformance.AllTrades.Count is greater than 0.

                        For example:

                        if (SystemPerformance.AllTrades.Count > 0 && myTradeCount != SystemPerformance.AllTrades.Count-1)
                        Paul H.NinjaTrader Customer Service

                        Comment


                          #13
                          Turns out the problem starts in this line

                          Code:
                          Trade lastTrade = SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count - 1];
                          Maybe we'll try a different way...because everything I have been doing has been based on the recommendation of the Ninjascript docs, but I also find those difficult to follow most of the time.

                          Let's focus on this and everything else should fall into place:

                          If my end goal is to draw on the chart the realized profit for each trade at the time of the close of each trade, what is the best way to go about that? The whole "systemperformance" syntax just feels...broken.

                          Thanks!
                          Last edited by Smoky; 01-14-2021, 09:30 PM.

                          Comment


                            #14
                            Hello Smoky,

                            Thanks for your reply.

                            I've attached a complete example for testing on your end.

                            Please apply to your historical TSLA data and test with the sim101 account.

                            This is basically the same as what I advised in post #2.

                            It will draw the trades PNL above or below the candle at the close of the trade. It will match the system performance report trades.

                            To import, go to Tools>import>Ninjascript add-on.

                            SystemPerformanceTestforSmoky.zip
                            Paul H.NinjaTrader Customer Service

                            Comment


                              #15
                              Ok that solved it. Using your example code I was able to see that I needed to execute this code block once, after all potential events had been calculated, not once per the possibility of an event (which were mutually exclusive anyway, but the code didn't like that).

                              Working now. Thank you!

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by DJ888, 04-16-2024, 06:09 PM
                              4 responses
                              12 views
                              0 likes
                              Last Post DJ888
                              by DJ888
                               
                              Started by terofs, Today, 04:18 PM
                              0 responses
                              11 views
                              0 likes
                              Last Post terofs
                              by terofs
                               
                              Started by nandhumca, Today, 03:41 PM
                              0 responses
                              7 views
                              0 likes
                              Last Post nandhumca  
                              Started by The_Sec, Today, 03:37 PM
                              0 responses
                              3 views
                              0 likes
                              Last Post The_Sec
                              by The_Sec
                               
                              Started by GwFutures1988, Today, 02:48 PM
                              1 response
                              9 views
                              0 likes
                              Last Post NinjaTrader_Clayton  
                              Working...
                              X