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

//do something// on daily bar close

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

    //do something// on daily bar close

    I'm sure this has been covered, but I cannot find a clear and concise sample of this logic in the limited time I searched for it.

    I'm running NT8 and am looking for an example of the following logic...

    Current situation:
    - A strategy is running daily bars.
    - At close of daily bar the strategy signals a long or short position.
    - A manual trade is placed at open of next daily bar.

    What I'm looking for: (an example to follow)
    - A strategy is running daily bars.
    - At close of daily bar the strategy signals a long or short position.
    - //do something - alert, sendmail, etc// at the time the daily bar closes (to prepare for manual trade entry the next day)
    - A manual trade is placed at open of next daily bar.

    Thanks,
    eleven

    #2
    Hello eleven, and thank you for your question.

    You can detect whether it is the end of the day, and whether you have taken an end of day action, with code similar to the following :

    Code:
    [FONT=Courier New]private bool doneEod = false;
    protected override void OnBarUpdate()
    {
        if (FirstBarOfSession)
        {
            doneEod = false
        }
    
        // e.g. 4 PM session close
        if (ToTime(Time[0]) > 160000 && ! doneEod)
        {
            doneEod = true;
            // do stuff here
        }
    }[/FONT]
    As far as what to replace "// do stuff here" with, I would like to recommend the SendMail method, documented here,



    You will want to review your SMTP settings in Tools -> Options -> Misc . This thread will have more information on the subject.

    http://www.ninjatrader.com/support/f...008#post262008

    Please let us know if there are any other ways we may help.
    Jessica P.NinjaTrader Customer Service

    Comment


      #3
      Thanks Jessica. Would the following code work to send an alert/email, etc.at bar close upon a long entry signal.

      Code:
      private bool doneEod = false;
      protected override void OnBarUpdate()
      {
          if (FirstBarOfSession)
          {
              doneEod = false
          }
      
          // e.g. 4 PM session close
          if (ToTime(Time[0]) > 160000 && ! doneEod)
          {
              doneEod = true;
              // do stuff here
          }
      }
      
      
      protected override void OnPositionUpdate(IPosition position)
      {
          if ((position.MarketPosition == MarketPosition.Long) && (doneEod == true))
          {
               // Alert/sendmail, etc.
          }
      }

      ...or would OnOrderUpdate() work once an order was placed?
      Last edited by eleven; 11-08-2016, 02:33 PM.

      Comment


        #4
        While what you are suggesting will work, I would highly recommend moving the end-of-day boundary to well before the actual end of the day, since your position must be able to change after your end-of-day boundary is reached for your code to execute.
        Jessica P.NinjaTrader Customer Service

        Comment


          #5
          Originally posted by NinjaTrader_JessicaP View Post
          While what you are suggesting will work, I would highly recommend moving the end-of-day boundary to well before the actual end of the day, since your position must be able to change after your end-of-day boundary is reached for your code to execute.
          Jessica,

          Would the opposite work as well by keeping the end-of-day boundary where it is at and moving the alert forward in time by 5 min or so? It might be easier for me to program with my limited programming skills.

          Thanks,
          eleven

          Comment


            #6
            The only way to make it possible to enter a position before the end of the day is if the time in this line of code,

            Code:
            [FONT=Courier New]    if (ToTime(Time[0]) > 160000 && ! doneEod)[/FONT]
            refers to a time before the market closes.
            Jessica P.NinjaTrader Customer Service

            Comment


              #7
              Jessica,

              I can use your suggest code to send me the alert prior the next day open. I understand that part.

              What I'm trying understand is the following:
              How can I determine if an entry signal was made, for the next open, at the close of a daily bar? Does the end of a daily bar need the open the next day to signal? If so, is there an example of the code (reference sample, etc.) that I can use to tailor to my strategy?

              thanks,
              Last edited by eleven; 11-09-2016, 04:35 PM.

              Comment


                #8
                Thank you for the additional information. I believe I may have misunderstood taking action at the close of a trading day with taking action at the close of a daily bar.

                NinjaTrader is truly event driven software. OnPositionUpdate will only ever be called when your position changes, and OnBarUpdate will only be called if a price changes. Because we can not guarantee prices will change toward the end of the day, to take action at the close of a trading day, we need a short range that covers the end of the day, and we need to ensure that we only take end of day action once, in order to take action at the close of a day. Taking action at the time a trade day ends will also require you to use, for example, minute bars, since with daily bars you can only take action after a trade day has ended.

                If you would rather not use minute bars, and would rather use daily bars, you can move the code I mentioned to OnMarketData, as follows :

                Code:
                protected override void OnMarketData(MarketDataEventArgs event)
                {
                    if (event.MarketDataType == MarketDataType.Last)
                    {
                        // do stuff
                    }
                }
                With that in mind, you mention wanting to know if an entry signal was made at the close of the day. You could continually update a variable in OnMarketData. This variable would then remain in the same state overnight as it was in at the close of the trading day. This can be done like so, regardless the bar type you are using :

                Code:
                private entryHappened = false;
                private Order entryStopOrLimit = null;
                protected override void OnMarketData(MarketDataEventArgs event)
                {
                    if (event.MarketDataType == MarketDataType.Last)
                    {
                        // closed entry order leaving us in a position
                        entryHappened = Position.MarketPosition != MarketPosition.Flat;
                
                        // working entry order
                        entryHappened |= entryStopOrLimit != null;
                    }
                }
                You would then need to store orders you placed away from the market price inside entryStopOrLimit .
                Last edited by NinjaTrader_JessicaP; 11-10-2016, 07:22 AM.
                Jessica P.NinjaTrader Customer Service

                Comment


                  #9
                  Thanks Jessica. That helps me out.

                  Comment


                    #10
                    Hi Jessica,
                    I have a very similar problem. I want to make calculations and send an email after the finishing of the daily bar. Using the OnMarketData() method is a good idea because the code hast to be outside the OnBarUpdate() method. I'm also thinking about using the OnConnectionStatusUpdate() method. Is there a method which is triggered right after the session end.

                    Could this if-condition be the solution for this problem?
                    if(connectionStatusUpdate.Status == ConnectionStatus.ConnectionLost)

                    Comment


                      #11
                      I am happy to help Redmoon22. While there is no code such as that you are suggesting, if you use the Default 24/7 template, you can then detect when sessions have ended while continuing to process data, and can thus launch events after the session. This forums link has more information.

                      Jessica P.NinjaTrader Customer Service

                      Comment


                        #12
                        Originally posted by NinjaTrader_JessicaP View Post
                        I am happy to help Redmoon22. While there is no code such as that you are suggesting, if you use the Default 24/7 template, you can then detect when sessions have ended while continuing to process data, and can thus launch events after the session. This forums link has more information.

                        http://www.ninjatrader.com/support/f...d.php?t=100732
                        Thanks Jessica, but I still have two questions:
                        1) How can I detect the session end?
                        2) Do you mean that with the Default 24/7 template my indicator continues to get OnMarket() Data after the session end?
                        Last edited by Redmoon22; 05-23-2017, 01:39 PM.

                        Comment


                          #13
                          I am happy to help Redmoon22.

                          How can I detect the session end?

                          In the code sample attached to that forums page, the code

                          Code:
                          [FONT=Courier New]
                          if (Time[0] < stop)[/FONT]
                          Means, in plain language, "if the current time is earlier than the session end" . Technically those are absolute times and we want relative times (in other words, we only care about hours, minutes, and seconds, and not the actual date). So while this code will work since stop and Time[0] are both regenerated every day, it would still be better coding practice to say

                          Code:
                          [FONT=Courier New]
                          if (ToTime(Time[0]) < ToTime(stop))[/FONT]
                          If we get in the habit of doing that we'll always be able to ignore the year, month, and day. I'll do that from now on. Detecting the session end is literally

                          Code:
                          [FONT=Courier New]
                          if (ToTime(Time[0]) == ToTime(stop))[/FONT]
                          However, since NinjaTrader's OnBarUpdate is tick rather than time driven, it's best to leave a little bit of a buffer when figuring out when the session ends. We can leave, for instance, a 10 second buffer on either side of the stop time like this :

                          Code:
                          [FONT=Courier New]
                          [B]private bool inSession = false;[/B]
                          protected override void OnBarUpdate()
                          {
                              DateTime start, stop[B], stopearly, stoplate[/B];
                          [B]    double buffer = 10.0;[/B]
                              Session.String2Session("CME US Index Futures RTH").GetNextBeginEnd(Time[0], out start, out stop);[B]
                              if (Bars.FirstBarOfSession)
                              {
                                  inSession = false;
                              }
                              stopearly = stoplate = stop;[/B][B]
                              stopearly.AddSeconds(-buffer);[/B][B]
                              stoplate.AddSeconds(buffer);
                          [/B]    if ([B]ToTime([/B]start[B])[/B] < [B]ToTime([/B]Time[0][B])[/B] && [B]ToTime([/B]Time[0][B])[/B] < [B]ToTime([/B]stop[B]early)[/B])
                              {
                          [B]        inSession = true;[/B]
                                  Print("In RTH");
                              }[B]
                              if (ToTime(stopearly) <= ToTime(Time[0]) && ToTime(Time[0]) <= ToTime(stoplate) && inSession)
                              {
                                  Print("At the end of the session");
                              }
                              if (ToTime(stopearly) <= ToTime(Time[0]))
                              {
                                  inSession = false;
                              }
                          [/B]}[/FONT]

                          2) Do you mean that with the Default 24/7 template my indicator continues to get OnMarket() Data after the session end?


                          Not necessarily. Your indicator will continue getting data with the Default 24/7 template as long as data is being generated by the market itself. A good way to guarantee that data continues being generated so that you can continue processing after the end of a session you are interested in, would be to use the Default 24/7 instrument with a forex series as your primary series, since those typically trade all the time. Some data providers also provide a ^TICK series for this purpose. You can learn more about multi instrument strategies here

                          Jessica P.NinjaTrader Customer Service

                          Comment


                            #14
                            Thanks a lot, Jessica. I have reviewed your Timer method and this has helped me to find a solution.

                            I have an acceptable solution way.. I am using the simple timer event. Doing the custom event with an in interval of 60 seconds.. the custom event has an if-condition which checks for a certain time "if ( ToTime(DateTime.Now) >= ToTime(22 , 0 , 0 ) ) ... I will try to combine this if-condition with the sessionIterator.ActualSessionEnd.. the triggered if-condition contains "Calculate = Calculate.OnEachTick;" which helps to get the Daily Close.. And also in the if conditions are the needed indicator calculations and the sendmail() method. After things are done the Calculation method is set back to "Calculate.OnBarClose"..

                            This is a "long" walk around, but it should work
                            A more elegant way would be to have a daily time schedule after the daily session end.
                            Is it possible to make a custom event trigger which triggers at a daily time schedule?

                            A custom triggered event depending on this if condition would be the best solution
                            ""if ( ToTime(DateTime.Now) >= ToTime(22 , 0 , 0 ) )"

                            Comment


                              #15
                              I am glad you were able to find a solution.

                              One thing I want to mention is that Time[0] is the time your script is currently processing, where DateTime.Now is the current processing time. For example, if OnBarUpdate is looking at a bar 10 minutes ago, Time[0] will be 10 minutes ago and DateTime.Now will be the current time.

                              To your question, since you are using the current time rather than the current bar time, you may refer to this section of the help guide which contains information on triggering custom events.

                              Jessica P.NinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by cre8able, Today, 03:20 PM
                              0 responses
                              1 view
                              0 likes
                              Last Post cre8able  
                              Started by Fran888, 02-16-2024, 10:48 AM
                              3 responses
                              45 views
                              0 likes
                              Last Post Sam2515
                              by Sam2515
                               
                              Started by martin70, 03-24-2023, 04:58 AM
                              15 responses
                              114 views
                              0 likes
                              Last Post NinjaTrader_Jesse  
                              Started by The_Sec, Today, 02:29 PM
                              1 response
                              7 views
                              0 likes
                              Last Post NinjaTrader_Jesse  
                              Started by jeronymite, 04-12-2024, 04:26 PM
                              2 responses
                              31 views
                              0 likes
                              Last Post NinjaTrader_BrandonH  
                              Working...
                              X