Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Starting to code

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

    Starting to code

    Hello,

    Starting to code with ninjatrader (I have good notions of programing, just starting to get used to C# and ninjatrader script editor) I have a question on 2lines of code:

    As an exercice to practice coding a strategy I want to enter a long position when the two bars before the current bar are bullish.

    Here is my code:

    if (High[2]<High[1])
    EnterLong(1,@"long_seb");

    I execute this code located in the OnbarUpdate() function on each tick.

    When I execute it I get trades that are taken even when the two previous bars are bearish and I don't know why.
    Also I should have lots of trades since its executing on each ticks but i get only few
    Any Help?

    Thanks




    Attached Files

    #2
    gotham Congratulations on starting to explore the amazing capabilities of NinjaScript.

    I'm sure others will comment specifically on your results, but a few comments on your settings and logic:
    • You should read and understand about "Entries per direction": https://ninjatrader.com/support/help...rdirection.htm
    • You should read and understand about "Entry handling": https://ninjatrader.com/support/help...ryhandling.htm
    • Once you are confident with the two settings above, consider appropriate values for them, given that the current code could conceivably submit an order on every tick of the current candle if the settings are not well thought out
    • The term "bullish" (and bearish, for that matter) needs to be defined explicitly. Although we can visually see what we interpret as bullish/bearish, coded logic requires explicit, rigid defining. For example, is two candles with consecutively higher Highs really bullish? Could be ... but not if the first High is also the Open and the Close is far below in the direction of Loss (for a Buy), and the following High is a peak on a wick that goes above the first High but price then plunges even further lower than the previous candle. Try to consider how Open/High/Low/Close all may be useful in determining bullish/bearish.
    Hope that helps.

    Thanks.
    Multi-Dimensional Managed Trading
    jeronymite
    NinjaTrader Ecosystem Vendor - Mizpah Software

    Comment


      #3
      Hello gotham,

      Welcome to the NinjaTrader forums!

      I also wanted to provide a link to some helpful resources on getting started.


      jeronymite is very helpful here in asking what you defining as bullish and bearish?
      Do you mean the previous bar closed higher than the previous bars high and the bar from 2 bars ago also closed higher than the previous bar's high?
      Do you mean the previous two bars are green bars where the close of the previous bar is greater than the close of 2 bars ago is greater than the open of 2 bars ago?
      Do you mean the high (which could be the wick) of the previous bar is greater than the high of 2 bars ago and the high of 2 bars ago is greater than the high of 3 bars ago?
      Chelsea B.NinjaTrader Customer Service

      Comment


        #4
        Thanks for all your feedbacks and helpful links.

        To explain more about the strategy I want to program:
        I want to take a long position on the current bar when the higher high of the previous bar is higher than the higher high of the bar just before.

        Here on the chart attached (every bar represents one hour) we notice the bar n°1 has a higher high lower than the higher high of the next bar n°2. Thus It’s taking a long trade on the bar n°3 which I want and I’am expecting

        But :
        On the bar n°4 I don’t know why it’s taking a long trade because the higher high of the bar n°2 is higher than the higher high of the bar n°3.

        An other Question: On the bar n°3 it’s taking only one trade. I was expecting that it would take other long trades on the bar n°3 after the first long trade is closed.

        Potential Solutions: I have looked at parameters EnteryHandling/Entry per position following your last post, It seems that what I am missing it’s not coming from these parameters. Maybe it’s the call of OnbarUpdate() that is doing different from what I am thinking it’s doing.

        Attached Files

        Comment


          #5
          gotham Bearing in mind things already mentioned above, some further thoughts:
          • Lots of ticks will generate lots of orders only if the two settings I mentioned above allow it; so the fact you seem to be limited to one order is not surprising if the default settings are used
          • Another setting that will be critical is Calculate; you seem to imply that you have (or want) it set to Calculate.OnEachTick, but you need to be sure you have set it to what you really want, since that will determine how frequently OnBarUpdate is invoked, and therefore how often you are able to submit orders or perform other actions
          • For a moment, assume your conditions have been met: higher highs as you want. How many orders do you want to submit in one bar, how frequently during the bar's evolution, and on what evolving conditions?
          • The cause of an order in your bar No 4 is not obvious from your descriptions; the only real way to determine what is happening is to look at your code. You can post it, if you like, or if you want to keep it private (perfectly fine), you may want to post pseudo-code that describes sections of relevant actions, or you may wish to send it privately to NinjaTrader Support, or ... ... But without the code, it is unlikely to be easy to see what is happening. Up to you.
          Thanks.
          Multi-Dimensional Managed Trading
          jeronymite
          NinjaTrader Ecosystem Vendor - Mizpah Software

          Comment


            #6
            Hello,

            Thanks for your post,
            You can see my code below:

            namespace NinjaTrader.NinjaScript.Strategies
            {
            public class higherhigh2strat : Strategy
            {
            protected override void OnStateChange()
            {
            if (State == State.SetDefaults)
            {
            Description = @"Enter the description for your new custom Strategy here.";
            Name = "higherhigh2strat";
            Calculate = Calculate.OnEachTick;
            EntriesPerDirection = 1;
            EntryHandling = EntryHandling.AllEntries;
            IsExitOnSessionCloseStrategy = true;
            ExitOnSessionCloseSeconds = 30;
            IsFillLimitOnTouch = false;
            MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
            OrderFillResolution = OrderFillResolution.Standard;
            Slippage = 0;
            StartBehavior = StartBehavior.ImmediatelySubmit;
            TimeInForce = TimeInForce.Gtc;
            TraceOrders = false;
            RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
            StopTargetHandling = StopTargetHandling.PerEntryExecution;
            BarsRequiredToTrade = 2;
            // Disable this property for performance gains in Strategy Analyzer optimizations
            // See the Help Guide for additional information
            IsInstantiatedOnEachOptimizationIteration = true;
            SL = 8;
            TP = 4;
            }
            else if (State == State.Configure)
            {
            AddDataSeries("ES 06-22", Data.BarsPeriodType.Minute, 60, Data.MarketDataType.Last);
            SetStopLoss(@"long_test", CalculationMode.Currency, SL, false);
            SetProfitTarget(@"long_test", CalculationMode.Currency, TP);
            }
            }

            protected override void OnBarUpdate()
            {
            if (BarsInProgress != 0)
            return;

            if (CurrentBars[0] < 2)
            return;

            // Set 1
            if (High[2] < High[1])
            {
            EnterLong(Convert.ToInt32(DefaultQuantity), @"long_test");
            }

            }

            Comment


              #7
              Hello gotham,

              It appears you have the idea of bars ago confused.

              0 bars ago is the currently updated bar. This could be the most recently fully closed bar if Calculate is OnBarClose, or the currently building bar if Calculate is .OnEachTick or .OnPriceChange.

              1 bars ago would be the previous bar. 2 bars ago would be two bars to the left of the currently updated bar.

              In your screenshot the bar labelled 3 where the entry appears at the open would be the bar after the submission bar fully closed (COBC) or could be the submission bar (COET or COPC) bars ago 0.
              The bar labelled 2 would either be the submission bar, bars ago 0 (COBC), or could be the previous bar, bars ago 1 (COET or COPC).
              The bar labelled 1 would either be the previous bar, bars ago 1 (COBC), or could be bars ago 2 (COET or COPC).

              Assuming COBC, the submission bar, bars ago 0, would be bar you have labelled 2.
              bars ago 1 would be the bar you have labelled 1.
              bars ago 2 would not be included with your screenshot and would be left of bar you have labelled 1.

              Use a print to understand the behavior.
              Below is a link to a forum post that demonstrates using prints to understand behavior.
              Please watch the video 'Debugging using prints with the Strategy Builder'.


              If this is the strategy builder, add the print to a condition set with no conditions. Print the time of the bar, a label with High[2] set in the string, then the value of the High with bars ago set to 2, a label for < High[1], then the value for the High with bars ago set to 1.

              Save the output from the output window to a text file, and include this as an attachment with your post.
              Chelsea B.NinjaTrader Customer Service

              Comment


                #8
                Hello,
                Thanks for your last post
                I am using COET,
                Question : with COET , High[0] is the higher high of the last closing bar right? I tought it would be the higher high of the current forming bar..

                Gotham

                Comment


                  #9
                  Hello Gotham,

                  If you are using Calculate.OnEachTick and the State is State.Realtime, High[0] is the current high of the currently building bar, not the last closed bar.

                  If the State is State.Historical, TickReplay would need to be necessary to trigger intra-bar actions, and 1-tick intra-bar granularity would be necessary for accurate intra-bar order fills.
                  Last edited by NinjaTrader_ChelseaB; 06-08-2022, 01:53 PM.
                  Chelsea B.NinjaTrader Customer Service

                  Comment


                    #10
                    Hello,

                    Yes I want to always use COET. I change my code with the condition if(High[1]<High[0]) Enterlong
                    instead of if(High[2]<High[1]) Enterlong.
                    It appeared the code is starting to execute as i want.
                    Few things that I try to understand:
                    with the trade is taken at the next forming bar and not at Bar 0? see the attached file the trade is executed after the Bar[0]

                    Thanks


                    Click image for larger version

Name:	question080622.PNG
Views:	136
Size:	240.9 KB
ID:	1204444

                    Comment


                      #11
                      Hello gotham,

                      Is this real-time or historical?

                      (Add a print to check the state Print("State: " + State); )

                      Is TickReplay enabled?

                      The output from TraceOrders and prints should give an answer. Please ensure TraceOrders is enabled, then save the output from the output window to a text file and provide this with your post.
                      Chelsea B.NinjaTrader Customer Service

                      Comment


                        #12
                        Hello,

                        Using a 100 tick chart with historical data, enabling tick replay and having my condition set like If(High[2]<High[1]) EnterLong, it is now working as I was expected. (I could not use a one hour chart cause it's too long to calculate).
                        Thanks for your support

                        gotham

                        Attached Files

                        Comment

                        Latest Posts

                        Collapse

                        Topics Statistics Last Post
                        Started by NullPointStrategies, 03-13-2026, 05:17 AM
                        0 responses
                        86 views
                        0 likes
                        Last Post NullPointStrategies  
                        Started by argusthome, 03-08-2026, 10:06 AM
                        0 responses
                        151 views
                        0 likes
                        Last Post argusthome  
                        Started by NabilKhattabi, 03-06-2026, 11:18 AM
                        0 responses
                        79 views
                        0 likes
                        Last Post NabilKhattabi  
                        Started by Deep42, 03-06-2026, 12:28 AM
                        0 responses
                        52 views
                        0 likes
                        Last Post Deep42
                        by Deep42
                         
                        Started by TheRealMorford, 03-05-2026, 06:15 PM
                        0 responses
                        59 views
                        0 likes
                        Last Post TheRealMorford  
                        Working...
                        X