• If this is your first visit, you will have to register before you can post. To view messages, please scroll below and select the forum that you would like to visits. Questions? Be sure to check out the Forum FAQ.

Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Reusing code in a Strategy

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

    Reusing code in a Strategy

    I am new to programming, and any help would be greatly appreciated.

    I would like to set aside a block of code to reuse numerous times in a strategy. I guess a subroutine.

    As an example, I would like to call on this code in different places within my strategy.


    ToTime(Time[0]) >= ToTime(6, 45, 0)
    && ToTime(Time[0]) < ToTime(12, 30, 0)
    && MACD(12, 26, 9).Diff[1] > 0
    && Open[0] == 0.005
    && Close[1] < 3


    My questions are:

    1) Where do I place this code in the strategy structure
    2) How is it named/referenced for multiple usages?

    Thanks!

    #2
    Hello ArmKnuckle,

    Thank you for your inquiry.

    If you're wanting to reuse a block of code over and over again in a strategy, what you could do is create your own custom method.

    I would suggest taking a look at this link for more information about creating methods in C# (NinjaScript is based off of C#): http://www.csharp-station.com/Tutorial/CSharp/Lesson05

    If you would like to create a custom method, make sure it is outside of the OnBarUpdate() method, but still contained within the class.

    I'm not quite sure what you would like to do with your code, however, here is a simple method, with a return type of bool, that will return true if the statement you provided is true or false if the statement is false.

    Code:
    private bool ThisIsAMethod() // you can name the method anything you want. "ThisIsAMethod" is just an example
    {
         if (ToTime(Time[0]) >= ToTime(6, 45, 0)
    	&& ToTime(Time[0]) < ToTime(12, 30, 0)
    	&& MACD(12, 26, 9).Diff[1] > 0
    	&& Open[0] == 0.005
    	&& Close[1] < 3) // if this is true, return true
              return true;
         else // if it's not true, return false
              return false;
    }
    To call this method in your code, you would just type ThisIsAMethod(). So, for example, if you would like to print the value that is returned by this method, you'd do this:
    Code:
    Print(ThisIsAMethod());
    This would print "True" or "False" depending on what is returned after the code in the method is executed.

    Please, let us know if we may be of further assistance.
    Zachary G.NinjaTrader Customer Service

    Comment


      #3
      I noticed that the code in private bool with addition of a true/false calculation attached.

      My goal is to use the code multiple times when creating an automated trading strategy.

      I do not need to have the code return a result. I am looking for a simple way to reuse the code and not have duplicate code typed "word for word" in the strategy.

      Does the creation of a method under the private bool still remain true without the true/false addition to the code?

      Comment


        #4
        Hello ArmKnuckle,

        Can you please provide an example of how you are wanting to re-use that block of code you have provided in your original post in your strategy?

        That block of code provided is going to evaluate either to true or false.

        Rather than typing that block of code everywhere, you can utilize a custom method to see if the statement is true or false and return true or false based on the result.

        When you call the method in your code, the method returns true or false based on how the statement in that method evaluates.

        Are you wanting the method to return something else or not return anything at all? If you do not want it to return anything, then you would not be able to utilize it in an if statement.

        I look forward to assisting further.
        Zachary G.NinjaTrader Customer Service

        Comment


          #5
          Originally posted by ArmKnuckle View Post
          I noticed that the code in private bool with addition of a true/false calculation attached.

          My goal is to use the code multiple times when creating an automated trading strategy.

          I do not need to have the code return a result. I am looking for a simple way to reuse the code and not have duplicate code typed "word for word" in the strategy.
          But the logic there is evaluating a condition which ultimately returns True or False.


          If you don't want to type it - put it in your windows buffer : highlight the text, then press "CNTRL+C" at the same time to "COPY", and then use "CNTRL+V" where ever you want it in your code.

          You probably don't need to call it multiple times.

          You can put your Time checks around everything you wish to do.

          Code:
          OnBarUpdate...
          {
              if (ToTime(Time[0]) >= ToTime(6, 45, 0)
          	&& ToTime(Time[0]) < ToTime(12, 30, 0) )
              {
          	//Perform other things in here
          
                  if( MACD(12, 26, 9).Diff[1] > 0
          	&& Open[0] == 0.005
          	&& Close[1] < 3) 
                  { //braces allow multiple statements to be run when the IF statement is true
                      //do things when the above is true
                      EnterLong(1);
                       Print ("We are long!");
                   }
          
                  if( MACD(12, 26, 9).Diff[1] < 0
          	&& Open[0] < 0.005
          	&& Close[1] > 3) 
                  {
                      //do things when the above is true
                      EnterShort(1);
                       Print ("We are short!");
                   }
          
               } // end time check 6:45 to 12:30
          
          
              if (ToTime(Time[0]) >= ToTime(13, 45, 0)
          	&& ToTime(Time[0]) < ToTime(15, 30, 0) )
              { 
                   //do things within these hours.
          
               }
          }

          Comment


            #6
            I would like to reuse that as a base of code, and then add other code onto that base.


            I am too new to code this properly in C#, but this is the idea:

            A simplified example:


            Open Trade
            BASE CODE + New_Code_01

            // (or)

            BASE CODE + New_Code_02

            // (or)

            BASE CODE + New_Code_03


            Close Trade
            Closing code typed here.


            I am looking for a way to create a reusable storage area (BASE CODE) for code so I do not have repeated code making for an overlong/complicated automated trading strategy.

            Is defining this code as a METHOD the correct way to reference this code multiple times in a strategy?

            Thanks again.
            Last edited by ArmKnuckle; 11-20-2015, 06:33 PM.

            Comment


              #7
              Then I guess you would type it in once...

              Save that strategy as "base_code". (right click, Save As)

              Then anytime you wish to start from there, open it up, and immediately do a "SAVE AS", "strategy_1".

              Use ";" in the code if the compiler complains about not having anything in there...

              like

              Code:
              if ToTime(Time[0]) >= ToTime(6, 45, 0)
              && ToTime(Time[0]) < ToTime(12, 30, 0)
              {
                  ;  
              }

              Comment


                #8
                Hello ArmKnuckle,

                Regardless, the code you have provided will evaluate only to true or false.

                Using the custom method example I have provided, you can call this custom method and still add additional code to it.

                Because this code will evaluate to either true or false, the custom method will have a bool return type to return true or false so your main code can utilize the result.

                As an example:
                Code:
                if (ThisIsAMethod() && /*other code*/)
                     // do something
                Please take a look at this MSDN page for more information about methods in C#: https://msdn.microsoft.com/en-us/library/ms173114.aspx

                As another example, let's say that you want to utilize the multiplication of 3 * 3 multiple times in your code. While this is just a simple example, I'll show how you can utilize a method for this.

                First, you'll want to create your custom method. Ensure it is outside of the OnBarUpdate() method but still inside of the class. You'll want a return type of int because 3 * 3 is 9, which is an int (integer).
                Code:
                private int ThreeTimesThree()
                {
                     return 3 * 3;
                }
                Now that you have this custom method, say you want to add the result to multiple variables. You can call the method and add the result to another number:
                Code:
                private int firstNumber = 0;
                private int secondNumber = 0;
                
                protected override void OnBarUpdate()
                {
                     firstNumber = ThreeTimesThree() + 5;
                     secondNumber = ThreeTimesThree() + 3;
                }
                Please, let me know if I may be of further assistance.
                Zachary G.NinjaTrader Customer Service

                Comment


                  #9
                  Originally posted by ArmKnuckle View Post
                  I would like to reuse that as a base of code, and then add other code onto that base.


                  I am too new to code this properly in C#, but this is the idea:

                  A simplified example:


                  Open Trade
                  BASE CODE + New_Code_01

                  // (or)

                  BASE CODE + New_Code_02

                  // (or)

                  BASE CODE + New_Code_03


                  Close Trade
                  Closing code typed here.


                  I am looking for a way to create a reusable storage area (BASE CODE) for code so I do not have repeated code making for an overlong/complicated automated trading strategy.

                  Is defining this code as a METHOD the correct way to reference this code multiple times in a strategy?

                  Thanks again.
                  That looks like you are looking for a "text substitution macro" facility. That concept does not exist in C#.

                  If you want to reuse code in C#, you write a "method" (or maybe even use a "property"). If you want to extend a method, you write a new method which calls the base method and then extends it with your new code.

                  You may want to read a primer on C#, though a study of the examples in the NinjaTrader documentation is what would pay the quickest dividends in terms of getting familiar with the concepts of C# as they are used in NinjaTrader.
                  Last edited by koganam; 11-23-2015, 10:41 AM.

                  Comment


                    #10
                    I have created a Custom Method outside of the OnBarUpdate(), as described.

                    Does the code contained within the Custom Method calculate at the same frequency as set for OnBarUpdate()?

                    Strategy calculate setting: Calculate = Calculate.OnEachTick

                    Will both the OnBarUpdate() code and the Custom Method code calculate OnEachTick?

                    Thanks in advance.
                    Last edited by ArmKnuckle; 02-19-2019, 01:04 PM.

                    Comment


                      #11
                      Hello ArmKnuckle,

                      Does the code contained within the Custom Method calculate at the same frequency as set for OnBarUpdate()?
                      Your custom method would only be called when you specifically call it, so if you are calling it from OnBarUpdate it would also be called at that frequency. If you are only calling the method inside of a condition in OnBarUpdate, it would instead be called at the frequency which the condition is true. I would highly suggest using a Print before the method in your logic to see how frequently its called.

                      For example, going off the previous example:

                      Code:
                      private int ThreeTimesThree()
                      {
                           return 3 * 3;
                      }
                      
                      protected override void OnBarUpdate()
                      {
                      Print("Calling my custom method at: " + Time[0]);
                           firstNumber = ThreeTimesThree() + 5;
                      }
                      This would output the text and time when your condition is called to give you an idea of how frequent this is happening.

                      Please let me know if I may be of additional assistance.


                      JesseNinjaTrader Customer Service

                      Comment

                      Latest Posts

                      Collapse

                      Topics Statistics Last Post
                      Started by StevenNelson, Today, 05:49 AM
                      1 response
                      4 views
                      0 likes
                      Last Post NinjaTrader_PatrickG  
                      Started by fx.practic, Today, 01:41 AM
                      0 responses
                      11 views
                      0 likes
                      Last Post fx.practic  
                      Started by wolfcuring, Today, 01:29 AM
                      0 responses
                      3 views
                      0 likes
                      Last Post wolfcuring  
                      Started by BrandonT1292, 06-17-2019, 03:03 PM
                      2 responses
                      30 views
                      0 likes
                      Last Post thinarthrill  
                      Started by cbentrikin, Yesterday, 07:46 PM
                      1 response
                      11 views
                      0 likes
                      Last Post NinjaTrader_Marco  
                      Working...
                      X