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

Defining the number of trade executions per session

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

    Defining the number of trade executions per session

    Referring to those posts - Paul redirection tNT7 -> NT8 Strategy Forum:
    NinjaTrader_PaulH
    Hi Paul,

    Could you please share the video again? Thanks a lot!

    About the previous link shared - it's dead:
    I'm getting the following from the link shared in post #2 above:
    https://ninjatrader.com/support/foru...%20/%3Et=15417
    Invalid Page URL. If this is an error and the page should exist, please contact the system administrator and tell them how you got this message.

    Do you have another access? Thanks a lot!


    Note on Videos archiving:
    https://ninjatrader.com/support/foru...-builder/page3

    #2
    Hello Cormick,

    Thanks for your post.

    Regrettably, you have misunderstood the other post and what the video showed (if it could have been seen!).

    The video would have shown how to create a user variable in NinjaTrader7 that was used as a bool variable. In NinjaTrader7 there are not specific variable types like NinjaTrader8 so that was why that video was made to help clarify that, at that time 5 years ago. It would be irrelevant for NinjaTrader8.

    Also, the NinjaTrader7 thread was about trading once per session and would not relate to your title of "Defining the number of trade executions per session".

    You are mixing too many links without understanding and this is causing more confusion and additional time to answer. Please take the approach of asking specific questions that you need help with rather than finding something that may not be related with links.

    The NinjaTrader7 video is no longer available.

    In NinjaTrader8 if you want to limit to one trade per session you would:

    1) Create a bool type variable, set to true
    2) In your entry set, add a condition to check that the bool is true
    3) in the action of the set, set the bool to false.
    4) In another set create the condition Misc>first bar of session, equal, Misc>true
    5) in that set, set the bool to true.

    No need for a video.

    Paul H.NinjaTrader Customer Service

    Comment


      #3
      Hi Paul,

      Thanks for the reply.


      Regrettably, you have misunderstood the other post and what the video showed (if it could have been seen!).

      See:
      Trading once per session

      03-30-2016, 08:59 AM
      Using the strategy wizard, how would I set a condition where only a defined number of entries per session were taken?

      I´d quite like to be able to define the number per session in the backtest preferences.


      ...
      If you want to have more than one trade per session then you would need to unlock your code and then in Ninjascript add a condition and variable tied to the number of trades you wish to limit to and either decrement or increment a counter. Once unlocked you would be unable to use the strategy wizard directly with that code.

      The video would have shown how to create a user variable in NinjaTrader7 that was used as a bool variable. In NinjaTrader7 there are not specific variable types like NinjaTrader8 so that was why that video was made to help clarify that, at that time 5 years ago. It would be irrelevant for NinjaTrader8.

      Ok for the user variable in NT7.

      Also, the NinjaTrader7 thread was about trading once per session and would not relate to your title of "Defining the number of trade executions per session".

      The title, yes - not the thread, if you reread the content and your own answers.

      Trading once per session

      03-30-2016, 08:59 AM
      Using the strategy wizard, how would I set a condition where only a defined number of entries per session were taken?

      I´d quite like to be able to define the number per session in the backtest preferences.
      https://ninjatrader.com/support/foru...sion#post85740

      ...
      https://ninjatrader.com/support/foru...382#post728382

      If you want to have more than one trade per session then you would need to unlock your code and then in Ninjascript add a condition and variable tied to the number of trades you wish to limit to and either decrement or increment a counter. Once unlocked you would be unable to use the strategy wizard directly with that code.

      You are mixing too many links without understanding and this is causing more confusion and additional time to answer. Please take the approach of asking specific questions that you need help with rather than finding something that may not be related with links.

      What mix of links are you referring to?

      No confusion — Specific question that I need:

      How can I set the number of trades per session to a definite number? For example 4 trades? If it's not specific enough - please tell me how to ask better.


      The NinjaTrader7 video is no longer available.

      Ok. Can you please make a new NT7 one (and archive it for the long run such that you won't need to redo it 5 years from now for other users)?

      In NinjaTrader8 if you want to limit to one trade per session you would:

      1) Create a bool type variable, set to true
      2) In your entry set, add a condition to check that the bool is true
      3) in the action of the set, set the bool to false.
      4) In another set create the condition Misc>first bar of session, equal, Misc>true
      5) in that set, set the bool to true.

      No need for a video.


      For the record, I can't use the Strategy Builder as I've already unlocked and added custom code to the strategy script.

      Ok. for the steps outline. I'll try that. Thanks.

      You mentioned the 'session Break' use here:
      I can't find 'session break' when searching the NT8 documentation.

      Can you tell/refer on how to use the 'session break' in NT8?

      A video is more appreciated, efficient and straightforward (less time to answer), and scalable (other users benefit more from it) as it was granted to previous ScottieDog user.
      Thanks a lot.

      Comment


        #4
        Hello Cormick,

        Thanks for your reply.

        My replies will remain focused on your specific questions for NinjaTrader8.

        I understand that you are now coding in Ninjascript so that is how I will reply.

        This is the question I will answer, "How can I set the number of trades per session to a definite number? For example 4 trades?"

        I would suggest creating a user input (int type) so that you can specify the number of trades you wish without having to recompile the strategy each time you want a different number of trades. You will also need to create an int type variable to act as a counter as well as an entry condition.

        For a psuedo code example, i will use TradeNumberLimit as the user input and NumberOfTrades as the counter.

        if (your conditions to enter and NumberOfTrades <= TradeNumberLimit)
        {
        // trade entry here
        NumberOfTrades++; // increment trade counter
        }

        Regarding, "I can't find 'session break' when searching the NT8 documentation." Please see: https://ninjatrader.com/support/help...rofsession.htm

        Paul H.NinjaTrader Customer Service

        Comment


          #5
          Hi Paul,

          thank you for your reply.

          I'll see what I can do with what you offer as solution.

          I'll be back when I hit an impasse.

          Thanks a lot!

          Comment


            #6
            Hi Paul,

            ABOUT USER INPUT CREATION IN UNLOCKED STRATEGY SCRIPT:
            I've search the NT8 documentation and the forum about 'creating a user input (int type)'.
            Creating User Defined Input Parameters

            The doc states:
            3.Scroll down to the bottom of the editor and expand the minimized "Properties" section by clicking on the + sign on the left.

            Problem:
            There is no expandable Properties block in my Script:
            https://i.imgur.com/LYKD81A.png

            What do you do to solve this issue?






            ABOUT THE COUNTER:

            I've search for counter and C# and found more about WHILE and FOR LOOPS.
            WHILE LOOP EXAMPLE:
            Click image for larger version  Name:	vmplayer_xwcy9c93wL.png Views:	0 Size:	398.3 KB ID:	1158957


            FOR LOOP EXAMPLE:
            Click image for larger version  Name:	vmplayer_UW1vAI4ng8.png Views:	0 Size:	93.1 KB ID:	1158958

            Here's my original code:

            Here's my WHILE LOOP code:
            Code:
            [LIST=1][*][INDENT]           [B]int NumberOfTrades = 1;[/B][*][INDENT]          [B] while (NumberOfTrades <= TradeNumberLimit)[/B]
            The WHILE LOOP code Only:
            [*][INDENT][B] {[/B][/INDENT][*][INDENT] if (((Time[0].DayOfWeek >= DayOfWeek.Monday) && (Time[0].DayOfWeek <= DayOfWeek.Wednesday))[/INDENT][*][INDENT] && (Times[0][0].TimeOfDay >= new TimeSpan(9, 30, 0))[/INDENT][*][INDENT] && (Times[0][0].TimeOfDay <= new TimeSpan(11, 50, 0))[/INDENT][*][INDENT] && High[0] > High[1])[/INDENT][*][INDENT] {[/INDENT][*][INDENT] EnterLongLimit(Convert.ToInt32(DefaultQuantity), GetCurrentBid(), "");[/INDENT][*][INDENT] StopLossModeLong = 0; [/INDENT][*][INDENT] }[/INDENT][*][INDENT] [B] NumberOfTrades++;[/B][/INDENT][*][INDENT][B] }[/B][/INDENT][/LIST]
            [/INDENT]






            Here's my FOR LOOP code:
            Code:
            [LIST=1][*][INDENT]           [B]for (int NumberOfTrades = 1; NumberOfTrades <= TradeNumberLimit; NumberOfTrades++)[/B]
            https://i.imgur.com/xNjQJgb.png Click image for larger version  Name:	vmplayer_Z04rX3vn5C.png Views:	0 Size:	365.2 KB ID:	1158960 The FOR LOOP code Only:
            [*][INDENT][B] {[/B][/INDENT][*][INDENT] if (((Time[0].DayOfWeek >= DayOfWeek.Monday) && (Time[0].DayOfWeek <= DayOfWeek.Wednesday))[/INDENT][*][INDENT] && (Times[0][0].TimeOfDay >= new TimeSpan(9, 30, 0))[/INDENT][*][INDENT] && (Times[0][0].TimeOfDay <= new TimeSpan(11, 50, 0))[/INDENT][*][INDENT] && High[0] > High[1])[/INDENT][*][INDENT] {[/INDENT][*][INDENT] EnterLongLimit(Convert.ToInt32(DefaultQuantity), GetCurrentBid(), "");[/INDENT][*][INDENT] StopLossModeLong = 0; [/INDENT][*][INDENT] }[/INDENT][*][INDENT] [B]}[/B][/INDENT][/LIST]
            You mentioned using the WHILE loop? Which is better for the use — WHILE or FOR loop?

            You didn't mention using WHILE or FOR loop wrappers in your pseudo code. Does NinjaScript accept WHILE or FOR loop wrappers?

            Anything else you see I'm not aware of that's needed for the code to work?


            Thanks a lot![/INDENT]
            [/INDENT]
            Last edited by Cormick; 06-05-2021, 10:29 AM.

            Comment


              #7
              Hi Cormick,
              I don't see a need for a loop here unless you want to place up to X (remaining allowed) trades per day at once.
              Step 1: UnderUnder Properties, add a User Input for max. allowed trades per day. Paul referred to this as "TradeNumberLimit".
              How to? Look at the SampleMACrossOver strategy, rows 72 et seq.
              Step 2: Above OnStateChange(), add a private int NumberOfTrades;
              Step 3: In State == State.SetDefaults, initialize NumberOfTrades via NumberOfTrades = 0;
              You can also define a default value for TradeNumberLimit here, e.g. via TradeNumberLImit = 5;
              Step 4: Before entering a trade, check that NumberOfTrades < TradeNumberLimit (see above, Paul already offered the code),
              Step 5: When you entered a trade, increment the counter via NumberOfTrades++;
              Step 6: In OnBarUpdate(), check if you have a new trading day, if yes, reset NumberOfTrades = 0; and start over.
              Watch-Out: You use a lot of limit orders, but you don't want to increment your counter before you really got filled. Otherwise, you could in theory end up with TradeNumberLimit attempts to trade per day, but without a single execution. To eliminate complexity, consider to start using market orders instead until the trade limit logic works as you would expect.
              Please use Print to Output Window all the time when developing. This is extremely helpful to see what your code does. In doubt for each individual step.
              What is the NumberOfTrades before you enter a trade? Does the counter increment after taking a trade? Does the daily reset work as expected?
              NT-Roland

              Comment


                #8
                Hi Roland,

                Thank you for your hand.

                THE COUNTER:

                I found this 'SampleTradeLimiter' code:
                I corrected my code accordingly (see the end of this post for snippets), with Market order as you suggested, here:
                EnterLong(); version:

                At first the code did execute up to 4 trades per session and the Break Even/trailing stop logic worked as expected, see screenshots:
                But after recompiling it stopped working — it executes now only 1 single trade per session and the Break Even/trailing stop logic doesn't work anymore/it exit at the session end only:

                Here a 1st short demo video:

                THE PRINT:

                I used the Print to Output window as you suggested — here a 2nd short demo video:
                I located the Print before and after the executing code in the video but it made no difference.

                The print shows zero trades while the chart shows some trades.

                Thanks for the guiding questions. Here's what I've done so far:

                What is the NumberOfTrades before you enter a trade?
                The Print outputs zero.

                Does the counter increment after taking a trade?
                I'm not sure if it does. How can I show it in the print?

                Does the daily reset work as expected?
                I'm not sure if it does. How can I show it in the print?

                Here's the Print code I used:
                Code:
                Print(string.Format("{0} | tradeCounter: {1}", Time[0], tradeCounter));


                EDIT1
                After reviewing the 2nd video, I located the correct time in Print and it does output — Here's a screenshot:
                https://i.imgur.com/Oj4KnG4.png

                Here's the output for the most recent trade:

                Code:
                01/06/2021 09:30:00 | tradeCounter: 1
                resetting tradeCounter


                But I'm not sure how that helps.
                What I see is that the counter does count 1 trade only. And the daily reset does work. But it does not increment?
                What would you suggest doing next?


                EDIT2:
                I just tested putting the Print code at the end of the Break Even/trailing stop logic and the output is the same, but I noticed other reset output at 11:00PM every day:

                Code:
                01/06/2021 09:30:00 | tradeCounter: 1
                resetting tradeCounter
                Code:
                02/06/2021 23:00:00 | tradeCounter: 0
                resetting tradeCounter
                Code:
                03/06/2021 23:00:00 | tradeCounter: 0
                resetting tradeCounter
                A 3rd demo short video:

                What more can we make out of it?


                Snippets:
                Code:
                 private int tradeCounter = 0; // This variable represents the number of trades taken per day.
                private int maxTrades = 4; // This variable sets the maximum number of trades to take per day.
                Code:
                 protected override void OnStateChange()
                {
                if (State == State.SetDefaults)
                {
                Description = @"Enter the description for your new custom Strategy here.";
                Name = "MultiStepBreakeven";
                Calculate = Calculate.OnEachTick;
                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;
                StopLossModeLong = 0;
                StopLossModeShort = 0;
                MaxTrades = 4;
                }
                else if (State == State.Configure)
                {
                }
                }
                Code:
                 // Reset the tradeCounter value at the first tick of the first bar of each session.
                if (Bars.IsFirstBarOfSession && IsFirstTickOfBar)
                {
                Print("resetting tradeCounter");
                tradeCounter = 0;
                }
                Code:
                 // If the amount of trades is less than the permitted value and the position is flat, go on to the next set of conditions.
                if (tradeCounter < MaxTrades && Position.MarketPosition == MarketPosition.Flat)
                {
                // Set 1
                /* If today is Monday or Tuesday from 9:30 to 11:50AM, and the current candle's High is greater than the previous,
                enter long market and increase the trade count by 1.
                In C#, ++ means increment by one. An equilivent would be tradeCounter = tradeCounter + 1; */
                if ((Time[0].DayOfWeek >= DayOfWeek.Monday && Time[0].DayOfWeek <= DayOfWeek.Tuesday)
                && (Times[0][0].TimeOfDay >= new TimeSpan(9, 30, 0))
                && (Times[0][0].TimeOfDay <= new TimeSpan(11, 50, 0))
                && High[0] > High[1])
                {
                tradeCounter++;
                EnterLong();
                StopLossModeLong = 0;
                }
                Code:
                 #region Properties
                [Display(GroupName="Parameters", Description="Maximum number of trades to take per day.")]
                public int MaxTrades
                {
                get { return maxTrades; }
                set { maxTrades = Math.Max(1, value); }
                }
                #endregion
                Attached Files
                Last edited by Cormick; 06-06-2021, 03:41 PM. Reason: Print at the end of Break Even/trailing stop logic test

                Comment


                  #9
                  Hello Cormick,

                  Thanks for your reply.

                  If I may suggest, your posts are difficult to follow with all of the links and it would be better if you would simply attach your .cs file directly, a screenshot if helpful, and a short description of what your question is. In general, the less redirecting the better when you are asking for help. We appreciate the videos and screenshots but these can be overwhelming when done excessively. I mean this respectfully and appreciate your consideration of these thoughts as it will help us to help you.

                  I have attached an example strategy to demonstrate a counter. You can apply this to ES 06-21, 1-minute bars, 5 days of data to simply test with the Ninjascript output window open.

                  mycustomstrategy2.zip


                  Paul H.NinjaTrader Customer Service

                  Comment


                    #10
                    Hi Paul,

                    Thank you for your reply.

                    My code updated with your .cs file is attached.

                    It still only executes one trade per session instead of the up to 4 expected. And The break even/trailing stop does not work.

                    Can you tell me please why the only 1 trade is executed instead of the up to 4 trades expected?

                    Can you tell me please why the break even/trailing stop does not work?

                    A screenshot is attached too.

                    Thank you.
                    Attached Files

                    Comment


                      #11
                      Hello Cormick,

                      Thanks for your reply.

                      Please note that we do not provide debugging services and we need you to be able to debug your own coding. You would use print statements that send their output to the new>Ninjascript output window. I have seen you use those tools so I know you are aware of them.

                      I know that debugging can be a tedious and frustrating process but if you are going to code your own then you need to develop your debugging process knowledge. You literally have to go line by line at ties to find out why something is not working as expected.

                      In looking at your code and applying it to a chart I can observe that it is placing only one order per day when the conditions are met and then the exit occurs only at the end of the session which means your stops are not being deployed at all.

                      Your stops are under this condition if (Position.MarketPosition == MarketPosition.Flat && TradesCounter < MaxTrades) which means they cannot perform because when you are in a position that line is no longer true, preventing the stops from being deployed. So this should be a simple fix to move your stops out from the { } associated with that line.





                      Last edited by NinjaTrader_PaulH; 06-07-2021, 08:41 AM. Reason: spelling
                      Paul H.NinjaTrader Customer Service

                      Comment


                        #12
                        Originally posted by NinjaTrader_PaulH View Post
                        Hello Cormick,

                        Thanks for your reply.

                        Please note that we do not provide debugging services and we need you to be able to debug your own coding. You would use print statements that send their output to the new>Ninjascript output window. I have seen you use those tools so I know you are aware of them.

                        I know that debugging can be a tedious and frustrating process but if you are going to code your own then you need to develop your debugging process knowledge. You literally have to go line by line at ties to find out why something is not working as expected.

                        In looking at your code and applying it to a chart I can observe that it is placing only one order per day when the conditions are met and then the exit occurs only at the end of the session which means your stops are not being deployed at all.

                        Your stops are under this condition if (Position.MarketPosition == MarketPosition.Flat && TradesCounter < MaxTrades) which means they cannot perform because when you are in a position that line is no longer true, preventing the stops from being deployed. So this should be a simple fix to move your stops out from the { } associated with that line.




                        Thanks Paul,

                        It works! You rock again!

                        I'm not good yet at interpreting and especially inferring from debugging. That requires foresight or/and a lot of debugging experience. I've only had the SimpleSMA strategy debugging example from Chelsea 301 and 401 2 webinars. I'll search the forum for more debugging examples. Thank you for any post or videos you know about that would boost my experience of debugging.

                        Just to make sure I understand what the issue was.
                        The script executes only if position is flat. Therefore once it enters the 1st trade and the position is no longer flat it won't execute the stop orders — Because stop orders are considered new positions. The stop orders are therefore evaluated as a positions as well. I previously assumed the stop/closing orders would not count as a new position (rather positions removers). Now I assume that exit orders are still positions (exiting positions).
                        Putting the stop orders outside the scope of the 'flat' condition works — Because the stops code now execute regardless of the position being flat or not.

                        You've been a great helper! Thank you very much.

                        The final code and screenshot are attached.

                        I'll now test live and be back with results.

                        Be well!
                        Attached Files

                        Comment


                          #13
                          Hello Cormick,

                          Thanks for your reply.

                          The stops would not execute after the entry because that stop coding was inside the block of the if statement that was checking for a flat position, when the entry filled the position was no longer flat.

                          The Stop coding would need to be outside of that if statement which you have now observed as functioning.



                          Paul H.NinjaTrader Customer Service

                          Comment


                            #14
                            Hi Paul,

                            Makes much sense. Of course! As long as the 1st trade is active it wouldn't execute next orders as it's not flat anymore! I didn't see it that way before, couldn't see the steps process correctly.
                            It's not that easy to see each step in relation to the next step.
                            The scope of the If statement must be limited to the entry conditions, then the exit conditions must not be. Thanks for making it clear.

                            I've traced back the origin of my if statement scope error. It was when I tried to use nested if statements to combine into a single strategy both the Long and Short scripts. That led to separating the Flat condition from the entry if statement conditions in order to nest the latter. Which was not the case in Jim's MultistepBreakeven code or in Kate's Trailing stop code — in both codes the Flat condition is associated with the entry if statement conditions.
                            (links used below so if I need to understand it later again, not to overwhelm, it's just that I noticed I tend to forget much more than I used to)
                            Jim's code:
                            Hello, I'm trying to incorporate a trailing stop into my strategy that always sits at the open of the previous candle, so long as it closes further into profit, if it doesn't I want the trail function to ignore it until the next profit candle. so for example: Trade enter Long -- stop loss @ low of entry candle Next bar

                            Kate's code:
                            Good afternoon, I would like through the strategy builder to be able to use the trailing stop, I don't know how to use it so that my stop decreases when I have advanced a certain number of ticks? Thanks

                            My wrong nested if code:
                            Good afternoon, I would like through the strategy builder to be able to use the trailing stop, I don't know how to use it so that my stop decreases when I have advanced a certain number of ticks? Thanks

                            I had lost track of that crucial nuance.

                            So now the final code doesn't need this separation. I attach it below. Again thanks a lot for your helping hand and great support!

                            Be well!
                            Attached Files

                            Comment


                              #15
                              Hi Paul,

                              Thank a lot for this great Print debugging video tutorial:



                              New Ideas:
                              Why not ask Chelsea to use this example for the next Strategy Builder 401 webinars? There's everything in it, how to check the bars with the ruler.

                              It would also be great to start Ninjatrader 8 coding video series, NT8Flix. It's badly needed! if compliance agrees. A lot of users would benefit from it!
                              Here I shared BingaZingas series example:

                              I'll browse for your other videos.




                              be well!
                              Last edited by Cormick; 06-08-2021, 12:09 PM. Reason: Series example

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by cre8able, 02-11-2023, 05:43 PM
                              3 responses
                              236 views
                              0 likes
                              Last Post rhubear
                              by rhubear
                               
                              Started by frslvr, 04-11-2024, 07:26 AM
                              8 responses
                              113 views
                              1 like
                              Last Post NinjaTrader_BrandonH  
                              Started by stafe, 04-15-2024, 08:34 PM
                              10 responses
                              46 views
                              0 likes
                              Last Post stafe
                              by stafe
                               
                              Started by rocketman7, Today, 09:41 AM
                              3 responses
                              11 views
                              0 likes
                              Last Post NinjaTrader_Jesse  
                              Started by traderqz, Today, 09:44 AM
                              2 responses
                              10 views
                              0 likes
                              Last Post NinjaTrader_Gaby  
                              Working...
                              X