Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Last trade profit

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

    #16
    Thank you very much. I will make it a variable above the signal. Now I know why it was not taking account the last trade until a trade later.
    Cheers!!

    Comment


      #17
      Originally posted by NinjaTrader_Kate View Post
      Hello Trader17,

      Yes, you can get the profit from the trade object returned:



      For example:

      double firstTradeProfitCurrency = SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count - 1].ProfitCurrency

      then you could check to see whether the returned value is positive or negative to determine whether the trade was a winning or losing trade.

      Please let us know if we may be of further assistance to you.
      Thanks Kate. And if I want to continue to see all the signals from the strategy and not just the trades taken after X losses I need to make another set of conditions with just "Draw" something?
      Thank you.

      Comment


        #18
        Hello Trader17,

        Thank you for your reply.

        Yes, you could certainly set something like that up, where a bool controls whether you're able to take trades and then after that if the bool has been triggered to stop trading, check that it's been triggered and have another set of conditions to just draw objects to show where signals would have occurred.

        Please let us know if we may be of further assistance to you.

        Comment


          #19
          Originally posted by NinjaTrader_Kate View Post
          Hello Trader17,

          Yes, you can get the profit from the trade object returned:



          For example:

          double firstTradeProfitCurrency = SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count - 1].ProfitCurrency

          then you could check to see whether the returned value is positive or negative to determine whether the trade was a winning or losing trade.

          Please let us know if we may be of further assistance to you.
          I got an error message trying it this way saying I am accessing an index with a value out of range. I tried it this way. Am I doing something wrong? It deos compile.

          Code:
          protected override void OnBarUpdate()
          {
          
          NinjaTrader.NinjaScript.BarsTypes.VolumetricBarsTy pe barsType = Bars.BarsSeries.BarsType as
          NinjaTrader.NinjaScript.BarsTypes.VolumetricBarsTy pe;
          
          if (barsType == null)
          return;
          
          if (BarsInProgress != 0)
          return;
          
          if (CurrentBars[0] < 5)
          return;
          
          
          double firstTradeProfitCurrency = SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count - 1].ProfitCurrency;
          
          double secondTradeProfitCurrency = SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count - 2].ProfitCurrency;
          
          // Set 1
          
          
          if ( Close[0] > Open[4] && firstTradeProfitCurrency > 0 && secondTradeProfitCurrency < 0 ) 
          {
          EnterLong(Convert.ToInt32(DefaultQuantity), "");
          }
          
          // Set 2
          if ( Close[0] < Close[4] && secondTradeProfitCurrency > 0 && firstTradeProfitCurrency < 0 )
          {
          EnterShort(Convert.ToInt32(DefaultQuantity), "");
          }
          
          }

          Comment


            #20
            Hello Trader17,

            Thank you for your reply.

            I believe this is occurring because you're checking the profit currency but not checking whether there have been any trades yet.

            I'd suggest trying something like this:

            Code:
             public class ExampleCheckForTrades : Strategy
            {
            private double firstTradeProfitCurrency;
            private double secondTradeProfitCurrency;
            protected override void OnStateChange()
            {
            if (State == State.SetDefaults)
            {
            Description = @"Enter the description for your new custom Strategy here.";
            Name = "ExampleCheckForTrades";
            Calculate = Calculate.OnBarClose;
            EntriesPerDirection = 1;
            EntryHandling = EntryHandling.AllEntries;
            IsExitOnSessionCloseStrategy = true;
            ExitOnSessionCloseSeconds = 30;
            IsFillLimitOnTouch = false;
            MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
            OrderFillResolution = OrderFillResolution.Standard;
            Slippage = 0;
            StartBehavior = StartBehavior.WaitUntilFlat;
            TimeInForce = TimeInForce.Gtc;
            TraceOrders = false;
            RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
            StopTargetHandling = StopTargetHandling.PerEntryExecution;
            BarsRequiredToTrade = 20;
            // Disable this property for performance gains in Strategy Analyzer optimizations
            // See the Help Guide for additional information
            IsInstantiatedOnEachOptimizationIteration = true;
            firstTradeProfitCurrency = 0;
            secondTradeProfitCurrency = 0;
            }
            else if (State == State.Configure)
            {
            }
            }
            
            protected override void OnBarUpdate()
            {
            
            // NinjaTrader.NinjaScript.BarsTypes.VolumetricBarsTy pe barsType = Bars.BarsSeries.BarsType as
            // NinjaTrader.NinjaScript.BarsTypes.VolumetricBarsTy pe;
            
            // if (barsType == null)
            // return;
            
            if (BarsInProgress != 0)
            return;
            
            if (CurrentBars[0] < 5)
            return;
            
            if (SystemPerformance.AllTrades.Count > 0)
            {
            firstTradeProfitCurrency = SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count - 1].ProfitCurrency;
            if (SystemPerformance.AllTrades.Count > 1)
            {
            secondTradeProfitCurrency = SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count - 2].ProfitCurrency;
            }
            }
            // Set 1
            
            
            if ( Close[0] > Open[4] && firstTradeProfitCurrency >= 0 && secondTradeProfitCurrency <= 0 )
            {
            EnterLong(Convert.ToInt32(DefaultQuantity), "");
            }
            
            // Set 2
            if ( Close[0] < Close[4] && secondTradeProfitCurrency >= 0 && firstTradeProfitCurrency <= 0 )
            {
            EnterShort(Convert.ToInt32(DefaultQuantity), "");
            }
            
            }
            }
            You'll notice that I've initialized the variables for firstTradeProfitCurrency and secondTradeProfitCurrency to 0 so they have an initial value when you try to reference them before any trades have been made. I've also changed the conditions so they can enter if no trades have yet been taken. The big change is that we are checking whether enough trades exist to reference in the AllTrades collection before trying to assign the currency values to firstTradeProfitCurrency and secondTradeProfitCurrency.

            Please let us know if we may be of further assistance to you.

            Comment


              #21
              Thank you so very much. I was going to try adding this code from the Guide to see if that was causing the indexing error.

              Code:
              if (SystemPerformance.AllTrades.Count > 1)
                {
                    Trade lastTrade = SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count - 1];
                    Trade firstTrade = SystemPerformance.AllTrades[0];
              
                    Print("The last trade profit is " + lastTrade.ProfitPercent);
                    Print("The first trade profit is " + firstTrade.ProfitPercent);
                }
              Do you think this might resolve the indexing error issue too?

              Thanks a lot.

              Comment


                #22
                Hello Trader17,

                Thank you for your reply.

                This would give you the first and last trade (if there's only one trade, it would return the same information twice). And yes, since it checks to see if there's been at least one trade, this would also avoid the indexing error.

                Please let us know if we may be of further assistance to you.

                Comment


                  #23
                  Sorry about that. I should have used -2 on the second line. So your way and this way should avoid the indexing issue?
                  Thanks a million!!

                  Comment


                    #24
                    So basically the strategy needs to start off with one or two trades to start the count. And can I take the same concept and use it not for the entire length of the strategy but just for the session? Can Strategy Builder do something like if first trade of session was a winner then stop trading or if first two were losers then stop taking trades for the session? Or an example script somewhere?

                    Thanks a lot Angel!!

                    Comment


                      #25
                      Hello Trader17,

                      Thank you for your reply.

                      Not in the Strategy Builder, no, but with custom coding that would be possible. Here's an example from our help guide that goes over how to cease trading after multiple losing trades in a manually coded strategy:



                      This script resets on the first bar of the session.

                      Please let us know if we may be of further assistance to you.

                      Comment


                        #26
                        Originally posted by NinjaTrader_Kate View Post
                        Hello Trader17,

                        Thank you for your reply.

                        I believe this is occurring because you're checking the profit currency but not checking whether there have been any trades yet.

                        I'd suggest trying something like this:

                        Code:
                         public class ExampleCheckForTrades : Strategy
                        {
                        private double firstTradeProfitCurrency;
                        private double secondTradeProfitCurrency;
                        protected override void OnStateChange()
                        {
                        if (State == State.SetDefaults)
                        {
                        Description = @"Enter the description for your new custom Strategy here.";
                        Name = "ExampleCheckForTrades";
                        Calculate = Calculate.OnBarClose;
                        EntriesPerDirection = 1;
                        EntryHandling = EntryHandling.AllEntries;
                        IsExitOnSessionCloseStrategy = true;
                        ExitOnSessionCloseSeconds = 30;
                        IsFillLimitOnTouch = false;
                        MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
                        OrderFillResolution = OrderFillResolution.Standard;
                        Slippage = 0;
                        StartBehavior = StartBehavior.WaitUntilFlat;
                        TimeInForce = TimeInForce.Gtc;
                        TraceOrders = false;
                        RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
                        StopTargetHandling = StopTargetHandling.PerEntryExecution;
                        BarsRequiredToTrade = 20;
                        // Disable this property for performance gains in Strategy Analyzer optimizations
                        // See the Help Guide for additional information
                        IsInstantiatedOnEachOptimizationIteration = true;
                        firstTradeProfitCurrency = 0;
                        secondTradeProfitCurrency = 0;
                        }
                        else if (State == State.Configure)
                        {
                        }
                        }
                        
                        protected override void OnBarUpdate()
                        {
                        
                        // NinjaTrader.NinjaScript.BarsTypes.VolumetricBarsTy pe barsType = Bars.BarsSeries.BarsType as
                        // NinjaTrader.NinjaScript.BarsTypes.VolumetricBarsTy pe;
                        
                        // if (barsType == null)
                        // return;
                        
                        if (BarsInProgress != 0)
                        return;
                        
                        if (CurrentBars[0] < 5)
                        return;
                        
                        if (SystemPerformance.AllTrades.Count > 0)
                        {
                        firstTradeProfitCurrency = SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count - 1].ProfitCurrency;
                        if (SystemPerformance.AllTrades.Count > 1)
                        {
                        secondTradeProfitCurrency = SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count - 2].ProfitCurrency;
                        }
                        }
                        // Set 1
                        
                        
                        if ( Close[0] > Open[4] && firstTradeProfitCurrency >= 0 && secondTradeProfitCurrency <= 0 )
                        {
                        EnterLong(Convert.ToInt32(DefaultQuantity), "");
                        }
                        
                        // Set 2
                        if ( Close[0] < Close[4] && secondTradeProfitCurrency >= 0 && firstTradeProfitCurrency <= 0 )
                        {
                        EnterShort(Convert.ToInt32(DefaultQuantity), "");
                        }
                        
                        }
                        }
                        You'll notice that I've initialized the variables for firstTradeProfitCurrency and secondTradeProfitCurrency to 0 so they have an initial value when you try to reference them before any trades have been made. I've also changed the conditions so they can enter if no trades have yet been taken. The big change is that we are checking whether enough trades exist to reference in the AllTrades collection before trying to assign the currency values to firstTradeProfitCurrency and secondTradeProfitCurrency.

                        Please let us know if we may be of further assistance to you.
                        Thanks Kate. This removed the indexing error for sure. I was using it with last two trades were losers then take the next trade. What i saw is that it is not going any further if say the last trade was a winner. While using this is Ninja Trader still looking at all trades taken across the entire data series? Because using it on another chart I saw many instances where there were 2 losers in a row and the strategy should have picked up trades. I know you do not debug but this is the simplest form of logic I tried using to test it before adding additional code. Like if close0 > close1 & firstTradeProfitCurrency <= 0 and secondTradeProfitCurrency <= 0 then go long. This can work on historical data too, correct?

                        Thanks a lot.

                        Comment


                          #27
                          Hello Kate. What I was thinking about that behavior is that a strategy does not store values for trades it does not take? That is why once a winner was seen I did not see it trade any further. Is there a way around that in Ninja to force it to store all trade values for PnL purposes but only take trades after say X losses in a row?
                          Thanks a bunch.

                          Comment


                            #28
                            Hello Trader17,

                            Thank you for your reply.

                            That's correct, it would only be getting values for trades taken. Trades not taken would not be tracked in the trade history since they were not taken. I would suggest turning on the TraceOrders function to see why it may not be taking trades when you'd expect.

                            Strategy Builder > Default Properties > More Properties > Trace Orders, or:

                            if (State == State.SetDefaults)
                            {
                            TraceOrders = true;
                            }

                            Once you then recompile the strategy, you can open a new NinjaScript Output window under New > NinjaScript Output. This will print a log of any orders submitted by the strategy during while it's running, along with any ignored orders. You can then look through and see what may be occurring.

                            Here is a link to our help guide that goes into more detail on tracing orders:

                            https://ninjatrader.com/support/help...aceorders2.htm

                            Trace orders alone may not give you the full picture of whether or not a trade should have been entered on a given bar, so adding prints to your strategy that will show in the NinjaScript Output window, with information on what the variables you're using for your conditions are on a particular bar, can be helpful.

                            This forum post goes into great detail on how to use prints to help figure out where issues may stem from — this should get you going in the correct direction. You can even add these using the Strategy Builder.

                            https://ninjatrader.com/support/foru...ns-not-working

                            If you run into issues like we saw here, the above information will allow you to print out all values used in the condition in question that may be evaluating differently. With the printout information you can assess what is different between the two.

                            Please let us know if we may be of further assistance to you.

                            Comment


                              #29
                              Thanks a lot Kate. My issue is not with taking trades properly. It is doing that correctly. But what I want to do is only take trades after X losses, yet want to see all trades on the chart. To make it simpler to explain I do not want it to stop trading after the very first sequence of X losses is broken. I want the strategy to keep going forward and keep looking for instances where there have been X looses in a row and take the next one.
                              Thanks a lot.

                              Comment


                                #30
                                Hello Trader17,

                                Thank you for your note.

                                The strategy would have actually have to have taken the losing trades to know there have been losses or to plot them on a chart. If you want to specifically take a trade after 3 losing other trades have been taken you could do so, by checking the previous trades as in the example and then entering if those have been losses.

                                Please let us know if we may be of further assistance to you.


                                Comment

                                Latest Posts

                                Collapse

                                Topics Statistics Last Post
                                Started by CarlTrading, 03-31-2026, 09:41 PM
                                1 response
                                72 views
                                0 likes
                                Last Post NinjaTrader_ChelseaB  
                                Started by CarlTrading, 04-01-2026, 02:41 AM
                                0 responses
                                39 views
                                0 likes
                                Last Post CarlTrading  
                                Started by CaptainJack, 03-31-2026, 11:44 PM
                                0 responses
                                63 views
                                2 likes
                                Last Post CaptainJack  
                                Started by CarlTrading, 03-30-2026, 11:51 AM
                                0 responses
                                63 views
                                0 likes
                                Last Post CarlTrading  
                                Started by CarlTrading, 03-30-2026, 11:48 AM
                                0 responses
                                53 views
                                0 likes
                                Last Post CarlTrading  
                                Working...
                                X