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

Return values

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

    Return values

    Hello,

    Can i store the current price in a variable using only strategy builder?
    Let me explain : I would like to have a variable let's say : double PriceWhenIStartTheStrategy = TakeTheCurrentPriceAndPutItInThisVariable(method that returns a double i guess). I would like this variable to execute only once when i start the strategy , then in conditions i want to put : if PriceWhenIStartTheStrategy < GetTheCurrentPrice wich it will be true if the price goes up go long .

    I am thinking this is not possible with strategy builder , because i cannot create a variable double which takes a method that gets the current price and returns a double. Maybe in the next version you will allow that in strategy builder. .
    If i have to code it where does my variable goes ? before the on stateChange() ?

    Can i ask my 999 questions that i have left inside this topic or i have to create one for every question?
    I dont have a strategy in mind i am just trying to understand this klingonian language called ninjascript. Try to answer the question assuming that i am stupid.



    #2
    Hello cosmin1ke,

    Thanks for your post.

    A double variable could be created in the Inputs and Variables screen of the Strategy Builder. Then, you could assign the current Close[0] price to that variable in the Actions section of the Conditions and Actions screen of the Builder. This variable could be used for other conditions/actions in your script.

    Strategy Builder: https://ninjatrader.com/support/help...gy_builder.htm

    You cannot create custom methods in the Strategy Builder. This would require unlocking the code from the Strategy Builder using the 'Unlock code' button and manually programming your custom method using C#.

    If you have further questions related to this specific topic, you could post those questions on this forum thread. Otherwise, please create new forum threads for each question you have that is not related to each other.

    NinjaTrader utilizes the C# programming language for developing indicators and strategies.

    The best way to begin learning NinjaScript is to use the Strategy Builder. With the Strategy Builder, you can set up conditions and variables and then see the generated code in the NinjaScript Editor by clicking the View Code button.

    Here is a link to our publicly available training videos, 'Strategy Builder 301' and 'NinjaScript Editor 401', for you to view at your own convenience.

    Strategy Builder 301 — https://www.youtube.com/watch?v=_KQF2Sv27oE&t=13s

    NinjaScript Editor 401 - https://youtu.be/H7aDpWoWUQs?list=PL...We0Nf&index=14

    I am also linking you to the Educational Resources section of the Help Guide to help you get started with NinjaScript:
    https://ninjatrader.com/support/help..._resources.htm

    If you are new to C#, to get a basic foundation for the concepts and syntax used in NinjaScript I would recommend this section of articles in our help guide first:
    https://ninjatrader.com/support/help...g_concepts.htm

    And the MSDN (Microsft Developers Network) C# Language Reference.
    https://ninjatrader.com/support/help...erence_wip.htm

    Let me know if I may assist further.
    Brandon H.NinjaTrader Customer Service

    Comment


      #3
      "A double variable could be created in the Inputs and Variables screen of the Strategy Builder. Then, you could assign the current Close[0] price to that variable in the Actions section of the Conditions and Actions screen of the Builder. This variable could be used for other conditions/actions in your script. "

      Are you sure i can assign in strategy builder Close[0] to a variable i created? I can evaluate (== ; < ; > ;!= and so on) a variable i created with the Close[0] but i don't see how i can assign it .
      OK. Can i make another post explaining why the quote above is confusing to say the least? Either my thinking is wrong or the quote above is confusing .Maybe you can see why my thinking is wrong or we can adapt the quote above to be more clear for our understanding.




      Comment


        #4
        Hello cosmin1ke,

        Thanks for your note.

        Yes, you could assign prices to a double variable in the Actions section of the Conditions and Actions screen of the Strategy Builder.

        See the forum threads linked below which contains examples that save prices to double variables in the Strategy Builder.

        https://ninjatrader.com/support/foru...596#post806596

        https://ninjatrader.com/support/foru...es#post1155153

        Let me know if I may assist further.
        Brandon H.NinjaTrader Customer Service

        Comment


          #5
          In your example https://ninjatrader.com/support/foru...596#post806596​ we have:

          Variables set to 0 : CurrentTriggerPrice and CurrentStopPrice
          Inputs set to 5 and -5 : TrailFrequency and TrailStopDistance

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

          if (CurrentBars[0] < 1)
          return;

          // Set 1
          if ((Position.MarketPosition == MarketPosition.Flat)
          && (State == State.Realtime))
          {
          EnterLong(Convert.ToInt32(DefaultQuantity), "");
          CurrentTriggerPrice = (Close[0] + (TrailFrequency * TickSize)) ;

          How does ninja know to put a stop order from the code below? We have a variable and inside is a number .How does ninja knows to put a stop order there?
          CurrentStopPrice = (Close[0] + (TrailStopDistance * TickSize)) ;
          }

          // Set 2

          if ((Position.MarketPosition == MarketPosition.Long)
          && (Close[0] > CurrentTriggerPrice))
          {
          CurrentTriggerPrice = (Close[0] + (TrailFrequency * TickSize)) ;
          CurrentStopPrice = (Close[0] + (TrailStopDistance * TickSize)) ;
          }

          // Set 3
          if (CurrentStopPrice != 0)
          {
          ExitLongStopMarket(Convert.ToInt32(DefaultQuantity ), CurrentStopPrice, @"", "");
          }

          Comment


            #6
            Hello cosmin1ke,

            CurrentStopPrice is assigned a price.

            CurrentStopPrice = (Close[0] + (TrailStopDistance * TickSize)) ;

            The variable is then supplied as the stop price to ExitLongStopMarket.

            ExitLongStopMarket(Convert.ToInt32(DefaultQuantity ), CurrentStopPrice, @"", "");

            The variable holds the price that was assigned to it. This is supplied as the stop price parameter to the order method which then uses price supplied as the stop price for the price of the stop.
            Chelsea B.NinjaTrader Customer Service

            Comment


              #7
              Another question: Calculation mode is OnEachTick
              Variables set to 0 : CurrentTriggerPrice and CurrentStopPrice
              Inputs set to 5 and -5 : TrailFrequency and TrailStopDistance



              if ((Position.MarketPosition == MarketPosition.Flat)
              && (State == State.Realtime))
              {
              EnterLong(Convert.ToInt32(DefaultQuantity), "");// here we are long
              CurrentTriggerPrice = (Close[0] + (TrailFrequency * TickSize)) ;// Assume current price at this moment is 100. So Close[0] is 100.
              Then CurrentTriggerPrice is 100 + (5 * 0.25)



              CurrentStopPrice = (Close[0] + (TrailStopDistance * TickSize)) ; // CurrentStopPrice = 100 + (-5 *0.25)
              }

              // Set 2
              //Below, if calulation is OnEachTick so all the if statements in OnBarUpdate() are executed with every tick why Close[0] is not 100 anymore?
              // How if statement are executed in relation to each tick?
              //

              if ((Position.MarketPosition == MarketPosition.Long)
              && (Close[0] > CurrentTriggerPrice))
              {
              CurrentTriggerPrice = (Close[0] + (TrailFrequency * TickSize)) ;
              CurrentStopPrice = (Close[0] + (TrailStopDistance * TickSize)) ;
              }

              // Set 3
              if (CurrentStopPrice != 0)
              {
              ExitLongStopMarket(Convert.ToInt32(DefaultQuantity ), CurrentStopPrice, @"", "");
              }

              The manual : Definition
              An event driven method which is called whenever a bar is updated. The frequency in which OnBarUpdate is called will be determined by the "Calculate" property.
              From which i understand that : If current price is 100 then Close[0] is 100 in all if statements. At the next tick price is 110 the Close[0] is 110 in all if statements and so on..

              Comment


                #8
                Hello cosmin1ke,

                Thanks for your note.

                "CurrentTriggerPrice = (Close[0] + (TrailFrequency * TickSize)) ;
                Then CurrentTriggerPrice is 100 + (5 * 0.25)"

                The sample code above would set the CurrentTriggerPrice to the Close price + 5 Ticks

                "CurrentStopPrice = (Close[0] + (TrailStopDistance * TickSize)) ; // CurrentStopPrice = 100 + (-5 *0.25)​"

                This would set the CurrentStopPrice to the Close price - 5 Ticks.

                This could be seen by using the Strategy Builder to offset the Close price by 5 ticks and clicking the 'View code' button. See the attached screenshots and the help guide page linked below.

                TickSize: https://ninjatrader.com/support/help...8/ticksize.htm

                When you are running a strategy with Calculate.OnEachTick, the logic in OnBarUpdate() will process for each incoming tick that occurs.

                If the strategy is not behaving as you expect it to, you must add debugging prints to the strategy that print out all the values being used in your script so you could compare them in a New > NinjaScript Output window. Once you fully understand exactly how the strategy is calculating values, you could modify your script accordingly.

                Below is a link to a forum post that demonstrates how to use prints to understand behavior.

                https://ninjatrader.com/support/foru...121#post791121

                Let us know if we may assist further.​
                Attached Files
                Brandon H.NinjaTrader Customer Service

                Comment


                  #9
                  Trying to understand how things work i encounter a problem.
                  I build in strategy builder a simple strategy : if current market position is flat then enter long. Calculation on each tick and everything else default. Nothing else.
                  When i run my strategy on MES nothing happens. My position tab shows nothing. But when i am in my strategy tab i see an average price 3765 i think which is not even close from the price in the chart. My position tab shows nothing but in position section from my strategy tab i have 1 long and in the same time realized or unrealized shows 0.
                  If i change the instrument whit absolute no other changes then it works.

                  Comment


                    #10
                    Screenshot when strategy is active.
                    Attached Files

                    Comment


                      #11
                      Hello cosmin1ke,

                      Thanks for your note.

                      Are you referring to historically calculated orders when you enable the strategy?

                      Does the strategy appear yellow in the Strategies tab of the Control Center when it is enabled?

                      When a strategy is yellow (or orange on some monitors) in the Strategies tab of the Control Center, this means that the strategy entered a historical (theoretical) position in the historical data that has been loaded. It also means that you have "Wait until flat" selected for the 'Start behavior' option in the strategy parameters.

                      When a strategy appears green in the Strategies tab of the Control Center, it is ready to place trades when the condition to do so becomes true.

                      Once the strategy has finished processing the historical data and has transitioned to real-time, it will wait until there is a real-time order submission that will cause the strategy to become flat. This also includes changing from a long position to a short position or vice versa as the position would pass through flat.

                      ​You can change the start behavior to "Immediately submit" in the parameters of the strategy. Immediately Submit automatically submits working orders from when the strategy processed historical data, and assumes the strategy position and account position are where you want it when you enable the strategy. This is typically used to have a strategy resume a position after disabling/enabling. If the strategy already had live orders running, the orders will resume with the new enablement of the strategy if they match the historically calculated orders. If the orders calculated from historical data do not match the live working orders, the live working orders will be cancelled and replaced by those calculated from historical data.

                      If you do not want the strategy to calculate a position from processing historical data. Simple add if (State == State.Historical) return; to the top of your strategy logic so historical processing is skipped. The strategy will then always start from a flat position because it has not calculated any orders.

                      See the help guide documentation below for more information.
                      Strategy vs. Account Position — https://ninjatrader.com/support/help..._account_p.htm
                      Start Behaviors — https://ninjatrader.com/support/help..._positions.htm

                      Additional information could be found in this forum thread - https://ninjatrader.com/support/foru...ion#post811541

                      Let me know if I may assist further.
                      Brandon H.NinjaTrader Customer Service

                      Comment


                        #12
                        How did i get into this situation? "this means that the strategy entered a historical (theoretical) position in the historical data that has been loaded."
                        I have 2 strategies that are the same. The only difference is the name. But one enters into "....historical (theoretical) position in the historical data that has been loaded." and the other does not.
                        Being the same the only way to know that one goes into a historical position , at least for me, is to activate and see that nothing happens.
                        I dont want to change the start behaviour or to add code (State == State.Historical) return; having two strategies absolute identical and having to modified one to behave like the other is confusing for a beginner like me.
                        So ... is there any other way to make the strategy not to enter in "a historical (theoretical) position in the historical data that has been loaded. a historical (theoretical) position in the historical data that has been loaded. " I tried to reset my data base but that didn't worked strangely enough. I can just delete it ,it's ok , but in this case the question below is the most important.
                        How did i get into this situation and what should i do to avoid that in the future?

                        Comment


                          #13
                          Hello cosmin1ke,

                          Thanks for your note.

                          Each time a strategy is enabled on a chart, it processes historical data to determine if the strategy has entered a historical (theoretical) position in the historical data that has been loaded.

                          If there is a slight difference in the historical data that has been loaded at the time you enable the strategy, the strategy may or may not calculate a historical position. For example, if you enable a strategy and it calculates a historical position, you disable the strategy. Then say 10 bars have passed since you disabled the strategy, then you re-enable the strategy and it does not calculate a historical position. This is because based on the extra 10 historical bars, the strategy calculated that it is not in a historical position.

                          If you enable the strategy and note that the strategy is yellow in the Strategies tab of the Control Center and the Strategy Position column has a value but the Account Position column does not, this means a historical position has been calculated. Once the strategy has finished processing the historical data and has transitioned to real-time, it will wait until there is a real-time order submission that will cause the strategy to become flat. This also includes changing from a long position to a short position or vice versa as the position would pass through flat.

                          Ultimately, if you do not want the strategy to calculate a position from processing historical data you could add if (State == State.Historical) return; to the top of your strategy's OnBarUpdate() logic so historical processing is skipped. The strategy will then always start from a flat position because it has not calculated any orders.

                          See the help guide documentation in post # 2 for more information about Start Behaviors and Strategy Position vs Account Position.

                          Let me know if I may assist further.
                          Brandon H.NinjaTrader Customer Service

                          Comment


                            #14
                            I have been looking on a sample code "SampleEnterOnceExitEveryTick " from your recommendations and the calculation is set to oneachtick but we can switch to onbarclose inside the code.
                            Is there a way to do it the other way around?
                            To have calculation set to onbarclose and the switch to oneachtick inside the code?

                            Comment


                              #15
                              Hello cosmin1ke,

                              Thanks for your note.

                              No, you must set the script to Calculate.OnEachTick or Calculate.OnPriceChange when splitting logic between Calculate.OnEachTick/OnPriceChange and Calculate.OnBarClose.

                              To calculate some values on each tick and others only on the close of a bar, you must set your host script to Calculate.OnEachTick and use if(IsFirstTickOfBar) and place all code that needs to calculate once every bar within that condition check. Then place all code that you want to calculate OnEachTick outside of the IsFirstTickOfBar condition check.

                              SampleEnterOnceExitEveryTick -https://ninjatrader.com/support/help...either_cal.htm

                              Please let us know if we may assist further.​
                              Brandon H.NinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by Vitamite, Yesterday, 12:48 PM
                              3 responses
                              17 views
                              0 likes
                              Last Post NinjaTrader_ChelseaB  
                              Started by aligator, Today, 02:17 PM
                              0 responses
                              12 views
                              0 likes
                              Last Post aligator  
                              Started by lorem, 04-25-2024, 09:18 AM
                              22 responses
                              95 views
                              0 likes
                              Last Post lorem
                              by lorem
                               
                              Started by sofortune, Today, 10:05 AM
                              3 responses
                              16 views
                              0 likes
                              Last Post NinjaTrader_ChristopherJ  
                              Started by ETFVoyageur, 05-07-2024, 07:05 PM
                              23 responses
                              185 views
                              0 likes
                              Last Post ETFVoyageur  
                              Working...
                              X