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

Set Stoploss on last bar close + counting trades

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

    Set Stoploss on last bar close + counting trades

    Hi together,

    i'm Daniel and i'm trying to create my own Ninjascript strategy.
    At first, excuse me for my english, it is not my mother tongue, but i hope you will understand me
    I traded some months with Ninjatrader and now i want to try it with automated strategies.
    I searched in some threads, maybe there is the solution, but it isn't.
    I use Ninjatrader 8.


    I have two questions or I need help in two situations:

    1.

    I want to set stoploss on the second last bar close, if i'm in a short position and the last three bars are decreasing. If the following bar is also decreasing, the stoploss should change to the actually second last bar close. Like a trailing stop.
    Only if we have three negative bars, stoploss should be changed.

    I think about the following solution, but it doesn't really work.
    Sometimes it works, but there are some times, if ninjatrader enter a short position and one second later the stoploss is actived and I'm flat again, why?



    if ((Position.MarketPosition==MarketPosition.Short)

    && (Close[0]<Close[1])
    && (Close[1]<Close[2])

    )

    {


    SetStopLoss(CalculationMode.Price, Close[2]);


    }

    2. How can I count the trades?

    I have created an int variable, which is count up one number after a short oder longentry, and then I compare this variable with an other one (my max. trades number) with an if comparison before the short or long order. But it also doesn't work.
    Sometimes NT trades more trades, and sometimes NT trades less trades than my "trades number" variable.

    What's the reason?


    I thank you very very much for your help!

    Daniel
    Last edited by pencil; 01-21-2017, 07:23 AM.

    #2
    Hello Daniel,

    Based on what you say is happening, it may be the price being used. I am unsure of the specifics but have you tried using Ticks instead of Price CalculationMode?

    SetStopLoss(CalculationMode.Ticks, 3);

    I could see in a short period of time perhaps the price had moved back up the stop and filled it if the price was very close.

    You may need to add Print statements in before the condition and print the prices when this occurs to really see what may have occurred. It also may help if you can go back in market replay and playback and pause the time to see how the logic was executed.

    Regarding counting trades, are you trying to count from when you submit the order or when it is actually filled? Potentially this has some influence in your logic? If you are trying to get Filled orders, you would likely need to use the OnExecutionUpdate override http://ninjatrader.com/support/helpG...ub=onexecution

    If you can provide more detail on the int system you are using now it may be more clear what is happening.

    I look forward to being of further assistance.
    JesseNinjaTrader Customer Service

    Comment


      #3
      Hi Jesse,

      thank you for your fast answer and excuse me for my late response please!

      First problem:

      I located the problem in another if condition for replacing the stoploss, there was the mistake. That other one sets the stoploss to an unplausible value and NT exit the position per stoploss directly after enter it.

      Thankyou anyway at this point! It was my fault.


      But the second problem is solved to half...and there appear another one...

      I wanted to count my trades with increasing a new variable "tradecount" after every entry.
      That logic is in OnBarUpdate method, and i know that NT restarts that method if a new bar was created.
      So i set the following if condition, for example (not the real paragraphs):



      if( Position != long, enter long == true)
      {
      enterlong;
      tradecount++;
      Print(tradecount)
      }


      It's only for testing...if i start that strategy in backtest mode and take a look at the output window, then i see, that Ninjatrader increase the tradecount more than 1 number after enter a trade position, why? The if condition isn't true after enter a position, anywhy NT go in there and increase tradecount value. I dont understand it.


      That "double execution" problem also happen if i want to exit a short position and after that i want to enter a long position directly at the same price at the same bar.
      That´s really strange, because NT exits the short position and enters TWO long positions, but only in realtime mode!! In backtest mode it works without problems, very dangerous.

      For example:

      if( condition 1 =true)
      {
      exitshort
      Print(exit Short + Time[0])
      }

      if( condition 1 =true, condition 2 =true)
      {
      enter long

      }

      The result:

      NT print in output window two times "exit Short" directly at the same time, exit the short position with entering a long position, starts (because two times) a new long position and then condition 2 is true and it enters another long position.

      So at the end my new position is two contracts long, that's a bad problem for the following trading.

      Note: condition 1 only can be true in one bar, it isn't true on the next bar. So Ninjatrader go into it two times at the same bar and that's the problem.

      I think NT starts the Onbarupdate method only once every new bar? But is isn't.


      I hope you understand me a little bit...thank you very much for your help.

      Daniel

      Comment


        #4
        Hello pencil,

        I couldn't say why the tradecount is increasing twice for each entry out of context but this may be related to your other problem.
        If you are seeing multiple calls to OnBarUpdate for the same bar that would not be expected. Could you provide the script you are using for me to see the logic being used? This would help me better understand what is happening.

        I look forward to being of further assistance.
        JesseNinjaTrader Customer Service

        Comment


          #5
          Hi Jesse!

          thank you again.

          I wanted to take a break for a few days to "reset my mind"
          But it wasn't possible, i had to find that mistake

          And now i think, i found it.

          I copied my complete logic into a new strategy file.
          In addition, a print command, which repeated the date and time in the output windows after every candle.

          Take a look what happens:

          Time: 26.01.2017 22:30:00
          Time: 26.01.2017 22:30:00
          Time: 26.01.2017 22:35:00
          Time: 26.01.2017 22:35:00
          Time: 26.01.2017 22:40:00
          Time: 26.01.2017 22:40:00
          Time: 26.01.2017 22:45:00
          Time: 26.01.2017 22:45:00
          Time: 26.01.2017 22:50:00
          Time: 26.01.2017 22:50:00
          Time: 26.01.2017 22:55:00
          Time: 26.01.2017 22:55:00
          That's probably the mistake, why NT makes curious things.

          Logic:

          {
          public class BO : Strategy
          {

          protected override void OnStateChange()
          {
          if (State == State.SetDefaults)
          {
          Description = @"T";
          Name = "BO";
          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.Day;
          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;

          }
          else if (State == State.Configure)
          {
          AddDataSeries("", Data.BarsPeriodType.Minute, 5, Data.MarketDataType.Last);

          //indicators

          }
          }

          protected override void OnBarUpdate()
          {
          if (CurrentBars[0] < 2)
          return;

          Print("Time: "+Time[0]);

          }

          #region Properties


          #endregion

          }
          }

          I delete comand for command and testing out if the problem appears again.
          At last i delete the marked paragraph and then the strategy works fine!!

          I put some indicators per drag&drop there, for backtesting my logic and so i put that command also there. Without think over it.

          Can you explain what that command does?


          AddDataSeries("", Data.BarsPeriodType.Minute, 5, Data.MarketDataType.Last);



          Edit:

          Another question is: Why prints NT the dates from two days, if I select one day in strategy analyzer? It´s the logic above which is working.

          Time: 23.01.2017 00:15:00
          Time: 23.01.2017 00:20:00
          Time: 23.01.2017 00:25:00
          Time: 23.01.2017 00:30:00
          Time: 23.01.2017 00:35:00
          Time: 23.01.2017 00:40:00
          Time: 23.01.2017 00:45:00
          Time: 23.01.2017 00:50:00
          Time: 23.01.2017 00:55:00
          Time: 23.01.2017 01:00:00
          Time: 23.01.2017 01:05:00
          Time: 23.01.2017 01:10:00
          Time: 23.01.2017 01:15:00
          ....
          Time: 23.01.2017 22:15:00
          Time: 23.01.2017 22:20:00
          Time: 23.01.2017 22:25:00
          Time: 23.01.2017 22:30:00
          Time: 23.01.2017 22:35:00
          Time: 23.01.2017 22:40:00
          Time: 23.01.2017 22:45:00
          Time: 23.01.2017 22:50:00
          Time: 23.01.2017 22:55:00
          Time: 23.01.2017 00:15:00
          Time: 23.01.2017 00:20:00
          Time: 23.01.2017 00:25:00
          Time: 23.01.2017 00:30:00
          Time: 23.01.2017 00:35:00
          Time: 23.01.2017 00:40:00
          Time: 23.01.2017 00:45:00
          .......
          Time: 23.01.2017 22:35:00
          Time: 23.01.2017 22:40:00
          Time: 23.01.2017 22:45:00
          Time: 23.01.2017 22:50:00
          Time: 23.01.2017 22:55:00

          Thank you for your fast assistance!!
          Last edited by pencil; 01-29-2017, 07:46 AM.

          Comment


            #6
            Hi,

            sorry for double posting, but the problem with double "buying" oder "selling" isn't fixed.

            I programmed a little strategy, which shows the mistake oder bug?!

            The result is that I'm trading with two contracts Short or Long, because "Position schliessen" and Entry Long/short" both are buying/selling two contracts together.
            But that only happens in Realtime mode! In Backtest, NT sell and buy only one contract.

            Here the code:
            #region Using declarations
            using System;
            using System.Collections.Generic;
            using System.ComponentModel;
            using System.ComponentModel.DataAnnotations;
            using System.Linq;
            using System.Text;
            using System.Threading.Tasks;
            using System.Windows;
            using System.Windows.Input;
            using System.Windows.Media;
            using System.Xml.Serialization;
            using NinjaTrader.Cbi;
            using NinjaTrader.Gui;
            using NinjaTrader.Gui.Chart;
            using NinjaTrader.Gui.SuperDom;
            using NinjaTrader.Gui.Tools;
            using NinjaTrader.Data;
            using NinjaTrader.NinjaScript;
            using NinjaTrader.Core.FloatingPoint;
            using NinjaTrader.NinjaScript.Indicators;
            using NinjaTrader.NinjaScript.DrawingTools;
            #endregion

            //This namespace holds Strategies in this folder and is required. Do not change it.
            namespace NinjaTrader.NinjaScript.Strategies
            {
            public class BO : Strategy
            { protected override void OnStateChange()
            {
            if (State == State.SetDefaults)
            {
            Description = @"T";
            Name = "BO";
            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.Day;
            TraceOrders = false;
            RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
            StopTargetHandling = StopTargetHandling.PerEntryExecution;
            BarsRequiredToTrade = 5;
            // Disable this property for performance gains in Strategy Analyzer optimizations
            // See the Help Guide for additional information
            IsInstantiatedOnEachOptimizationIteration = true;

            }
            else if (State == State.Configure)
            {
            //AddDataSeries("", Data.BarsPeriodType.Minute, 5, Data.MarketDataType.Last);

            //indicators

            }
            }

            protected override void OnBarUpdate()
            {
            if (CurrentBars[0] < 2)
            return;

            if ( Close[0]<Open[0] && Close[1]< Open[1])

            {
            if(Position.MarketPosition==MarketPosition.Long)
            {
            ExitLong(Convert.ToInt32(1), @"Exit Long", "");
            }
            EnterShort(Convert.ToInt32(1), @"Entry Short");
            Print("Entry Time: "+Time[0]);

            }

            if ( Close[0]>Open[0] && Close[1]> Open[1])

            {
            if(Position.MarketPosition==MarketPosition.Short)
            {
            ExitShort(Convert.ToInt32(1), @"Exit Short", "");
            }
            EnterLong(Convert.ToInt32(1), @"Entry Long");
            Print("Entry Time: "+Time[0]);

            } }
            #region Properties
            #endregion
            }
            }


            And here the screenshot:

            Click image for larger version

Name:	test.jpg
Views:	1
Size:	30.4 KB
ID:	881886



            Thank you!!

            Comment


              #7
              I believe this would be caused by how you have the logic formed:

              Code:
              if(Position.MarketPosition==MarketPosition.Short)
              {
              ExitShort(Convert.ToInt32(1), @"Exit Short", "");
              }
              EnterLong(Convert.ToInt32(1), @"Entry Long");
              Print("Entry Time: "+Time[0]);
              In this case, you are only checking if you are short and exiting but you are always entering after the exit. This would also not allow for the position to update inbetween calls which would cause for a double exit plus an entry. You would likely need to form the logic to choose to either exit, or reverse:


              Code:
              if(Position.MarketPosition==MarketPosition.Short)
              {
                  ExitShort(Convert.ToInt32(1), @"Exit Short", "");
              } 
              else if(Position.MarketPosition==MarketPosition.Flat)
              {
                  EnterLong(Convert.ToInt32(1), @"Entry Long");
                  Print("Entry Time: "+Time[0]);
              }
              This extra check would prevent cases where the Exit and Entry are happening in the same bar.

              Regarding AddDataSeries, this adds a second data series that can be used by the script. For example if you applied the script to a 1 minute chart, and then added a 1 tick series, the script could use both 1 minute increments and 1 tick increments. You would have to program the script to use this type of logic specifically, we have some help on this subject here: http://ninjatrader.com/support/helpG...=AddDataSeries

              I look forward to being of further assistance.
              JesseNinjaTrader Customer Service

              Comment


                #8
                Thank you!

                I don't need the second data series, so i removed it from the script and that's fine.


                Thank you also for the idea with checking if position is flat, before entry a new position. I have tried that before, but NT don't enter a new position after the exit from the other position and that's not my plan. I want to exit and enter positions on the same bar close.

                But sometimes I use an other if condition before entering after the exit, and it's not working with the reverse command...

                Have you some other ideas for me?

                Comment


                  #9
                  Hello Daniel,

                  If you are trying to reverse the position, you would not need to use the Exit statements at all. By default calling EnterLong or EnterShort while you are in an opposite position will exit the current position and enter into the opposite direction. By using both ExitLong and EnterShort or ExitShort and EnterLong on the same bar, you effectively duplicate the exit logic. You would need to use one or the other but not both to reverse a position.

                  If you remove the Exit logic and only use the Enter statements, you should see that when calling the opposite Enter statement the strategy reverses its position. If you are not in a position, it would simply enter into the direction you specify.

                  I look forward to being of further assistance.
                  JesseNinjaTrader Customer Service

                  Comment


                    #10
                    Hi Jesse, thank you for that information, it was very helpful, i think that was the point!

                    Originally posted by NinjaTrader_Jesse View Post

                    If you remove the Exit logic and only use the Enter statements, you should see that when calling the opposite Enter statement the strategy reverses its position. If you are not in a position, it would simply enter into the direction you specify.

                    Can you see a reason why NT prints the whole day two times to the output window
                    in ONE day backtest mode?

                    Decribed in my post at 01-29-2017 01:22 PM.


                    Thank you very much!

                    Daniel

                    Comment


                      #11
                      Hello Daniel,

                      Are you by chance running an Optimization instead of a Backtest specifically? In the case of an Optimization, there would be multiple same prints due to running multiple tests. I cannot see any other reason why you would get duplicate prints aside from the fact that you were originally testing with an added data series, now that you have removed the secondary series are you still seeing the same duplicate results?

                      I look forward to being of further assistance.
                      JesseNinjaTrader Customer Service

                      Comment


                        #12
                        There is running backtesttype "Standard".


                        With the command which added the second data series, NT repeated every bar.
                        Now without the ADD command NT repeats the whole day. That's the difference, which i liked to disable.
                        I chose for example the 23. January for backtesting day and NT printed the whole day two times.

                        I'm thinking about the strategy logic by myself, but i can't actually see the problem.
                        I don't think, this situation has any influence on my logic, but i would still like to solve it.

                        Comment


                          #13
                          Hello pencil,

                          I am still unsure of the result you are explaining, could you export the script as you have it now along with the output you get from running it in the analyzer? Potentially you have made some change to the script inbwtween posts that I am not seeing here.

                          When using the AddDataSeries, you were getting the expected result as you had two series being processed. With only a primary series and no calls to AddDataSeries, if there is only 1 print in OnBarUpdate you should see 1 print per bar. You could make a second test with only a print in OnBarUpdate and run a backtest to see this.

                          I look forward to being of further assistance.
                          JesseNinjaTrader Customer Service

                          Comment


                            #14
                            Originally posted by NinjaTrader_Jesse View Post
                            Hello pencil,

                            I am still unsure of the result you are explaining, could you export the script as you have it now along with the output you get from running it in the analyzer?
                            Hello, of course I can.

                            It's only for my understanding.
                            I run backtest mode standard, for example on the 01.02.2017. Only one day.

                            That simple strategy (doesn't make much sense, it's only for testing):

                            #region Using declarations
                            using System;
                            using System.Collections.Generic;
                            using System.ComponentModel;
                            using System.ComponentModel.DataAnnotations;
                            using System.Linq;
                            using System.Text;
                            using System.Threading.Tasks;
                            using System.Windows;
                            using System.Windows.Input;
                            using System.Windows.Media;
                            using System.Xml.Serialization;
                            using NinjaTrader.Cbi;
                            using NinjaTrader.Gui;
                            using NinjaTrader.Gui.Chart;
                            using NinjaTrader.Gui.SuperDom;
                            using NinjaTrader.Gui.Tools;
                            using NinjaTrader.Data;
                            using NinjaTrader.NinjaScript;
                            using NinjaTrader.Core.FloatingPoint;
                            using NinjaTrader.NinjaScript.Indicators;
                            using NinjaTrader.NinjaScript.DrawingTools;
                            #endregion

                            //This namespace holds Strategies in this folder and is required. Do not change it.
                            namespace NinjaTrader.NinjaScript.Strategies
                            {
                            public class BO : Strategy
                            {

                            protected override void OnStateChange()
                            {
                            if (State == State.SetDefaults)
                            {
                            Description = @"T";
                            Name = "BO";
                            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.Day;
                            TraceOrders = false;
                            RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
                            StopTargetHandling = StopTargetHandling.PerEntryExecution;
                            BarsRequiredToTrade = 5;
                            // Disable this property for performance gains in Strategy Analyzer optimizations
                            // See the Help Guide for additional information
                            IsInstantiatedOnEachOptimizationIteration = true;

                            }
                            else if (State == State.Configure)
                            {

                            }
                            }



                            protected override void OnBarUpdate()
                            {
                            if (CurrentBars[0] < 2)
                            return;



                            if ( Close[0]<Open[0] && Close[1]< Open[1])

                            {


                            EnterShort(Convert.ToInt32(1), @"Entry Short");
                            //Print("Entry Time: "+Time[0]);

                            }


                            if ( Close[0]>Open[0] && Close[1]> Open[1])

                            {


                            EnterLong(Convert.ToInt32(1), @"Entry Long");
                            //Print("Entry Time: "+Time[0]);

                            }


                            Print("Entry Time: "+Time[0]);

                            }

                            #region Properties


                            #endregion

                            }
                            }



                            I test it with 60min bars, so the problem is easier to see.

                            Output window:

                            Entry Time: 01.02.2017 03:00:00
                            Entry Time: 01.02.2017 04:00:00
                            Entry Time: 01.02.2017 05:00:00
                            Entry Time: 01.02.2017 06:00:00
                            Entry Time: 01.02.2017 07:00:00
                            Entry Time: 01.02.2017 08:00:00
                            Entry Time: 01.02.2017 09:00:00
                            Entry Time: 01.02.2017 10:00:00
                            Entry Time: 01.02.2017 11:00:00
                            Entry Time: 01.02.2017 12:00:00
                            Entry Time: 01.02.2017 13:00:00
                            Entry Time: 01.02.2017 14:00:00
                            Entry Time: 01.02.2017 15:00:00
                            Entry Time: 01.02.2017 16:00:00
                            Entry Time: 01.02.2017 17:00:00
                            Entry Time: 01.02.2017 18:00:00
                            Entry Time: 01.02.2017 19:00:00
                            Entry Time: 01.02.2017 20:00:00
                            Entry Time: 01.02.2017 21:00:00
                            Entry Time: 01.02.2017 22:00:00
                            Entry Time: 01.02.2017 03:00:00
                            Entry Time: 01.02.2017 04:00:00
                            Entry Time: 01.02.2017 05:00:00
                            Entry Time: 01.02.2017 06:00:00
                            Entry Time: 01.02.2017 07:00:00
                            Entry Time: 01.02.2017 08:00:00
                            Entry Time: 01.02.2017 09:00:00
                            Entry Time: 01.02.2017 10:00:00
                            Entry Time: 01.02.2017 11:00:00
                            Entry Time: 01.02.2017 12:00:00
                            Entry Time: 01.02.2017 13:00:00
                            Entry Time: 01.02.2017 14:00:00
                            Entry Time: 01.02.2017 15:00:00
                            Entry Time: 01.02.2017 16:00:00
                            Entry Time: 01.02.2017 17:00:00
                            Entry Time: 01.02.2017 18:00:00
                            Entry Time: 01.02.2017 19:00:00
                            Entry Time: 01.02.2017 20:00:00
                            Entry Time: 01.02.2017 21:00:00
                            Entry Time: 01.02.2017 22:00:00

                            Why double printing the whole day?


                            Thank you Jesse!!

                            Comment


                              #15
                              Hello Daniel,

                              I tried the sample and I am only seeing one printed day with no repeats. Can you tell me, are you updated to 8.0.4.0 currently or are you using a prior release?

                              I look forward to being of further assistance.
                              JesseNinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by Aviram Y, Today, 05:29 AM
                              0 responses
                              5 views
                              0 likes
                              Last Post Aviram Y  
                              Started by quantismo, 04-17-2024, 05:13 PM
                              3 responses
                              27 views
                              0 likes
                              Last Post NinjaTrader_Gaby  
                              Started by ScottWalsh, 04-16-2024, 04:29 PM
                              7 responses
                              36 views
                              0 likes
                              Last Post NinjaTrader_Gaby  
                              Started by cls71, Today, 04:45 AM
                              0 responses
                              6 views
                              0 likes
                              Last Post cls71
                              by cls71
                               
                              Started by mjairg, 07-20-2023, 11:57 PM
                              3 responses
                              219 views
                              1 like
                              Last Post PaulMohn  
                              Working...
                              X