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

NT8 storing the value of a variable, and changing the value of a variable or input

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

    NT8 storing the value of a variable, and changing the value of a variable or input

    Hello !
    I have a few problems, with storing the value of a variable or input, and changing the value of a variable or input.

    So, i'm trying to create a strategy that will use the value of a fib extension to use it as a target, and the strategy is creating her own fibonnaci extensions, its working like this :
    I have 3 input, where i place manually the 3 price level for the points of the extension (i'm not using the time), but, in a example where i can be long, but the price don't go right away with me, the price can break the low where the third point and input of the extension is, so the strategy need to readjust the point.

    The idea, is that when the low is break, the third point of the extension will be change to the new actual low of Low[0], and if the new low is also break, it will keep adjusting, until i get stopped out, or that we have a real low.
    Here's the code, and the explains below :

    protected override void OnBarUpdate()
    {
    // Fib Extension tracé pour calculer le point de target
    if (State == State.Historical);
    {
    ValeurAjustement3PointFibExtension = (Valeur3PointFibExtension);
    Draw.FibonacciExtensions(this, @"FibAutoTrailStoplongshortFibonacci extensions_1", false, 0, Valeur1PointFibExtension, 0, Valeur2PointFibExtension, 0, Valeur3PointFibExtension);
    }
    // Si long, et que le troisième point de l'extension est plus basse que le deuxième, et que le troisième point est casser vers le bas, le troisième point continueras d'être changer sur le nouveau low après sa cassure.
    if ((PositionAccount.MarketPosition == MarketPosition.Long)
    && (Close[0] < ValeurAjustement3PointFibExtension))
    {
    PlaySound(NinjaTrader.Core.Globals.InstallDir + @"\sounds\Alert1.wav");
    if ( CurrentBar < 1)return;
    RemoveDrawObject("FibAutoTrailStoplongshortFibonac ci extensions_1");
    ValeurAjustement3PointFibExtension = (Low[0]);
    Draw.FibonacciExtensions(this, @"FibAutoTrailStoplongshortFibonacciAjustement extensions_1", false, 0, Valeur1PointFibExtension, 0, Valeur2PointFibExtension, 0, ValeurAjustement3PointFibExtension);
    }

    What i did, is that we have the basic public double Valeur3PointfFibExtension, the point that could need a adjustment and where we set the price level before, and the private double ValeurAjustement3PointFibExtension, take the value of Valeur3PointFibExtension. What i'm trying to do, is that if the low of ValeurAjustement3PointFibExtension is broken, the price will take the new actual low, but the problem, is that, the value is set to the Low[0], and in my mind, since to be trigger, we need to have the price that go below the value of the double, the change in the value will not happen, and stay at the exact low.
    But the strategy, dont keep in memory the value that didn't get break, and will only set the value to the low of the open bar, since the = (Low[0]) is permanent.
    So, is there a way to either, modify the value of ValeurAjustement3PointFibExtension each time the If is triggered, and that the value will stay the same and not move if the if is not triggered, even if there is new bars created (i found the Value.Set option, but i dont think its working on NT8). Or, to keep in memory the value that didn't get break for ValeurAjustement3PointFibExtension.

    Thanks a lot ! If you need more of the code, its not a problem

    Ps : at a certain point, the strategy could not compile without if ( CurrentBar < 1)return; and i understand that its really important, but why is it important, and how do is it work ?

    #2
    Hello Robinson94,

    I'm attempting to reduce your inquiry to the relevant information.

    There is a double variable named ValeurAjustement3PointFibExtension.

    This is inititally set to the value of Valeur3PointFibExtension on each new bar as long as the script is processing historical data.
    ValeurAjustement3PointFibExtension = (Valeur3PointFibExtension);

    Then used for a condition.

    if ((PositionAccount.MarketPosition == MarketPosition.Long)
    && (Close[0] < ValeurAjustement3PointFibExtension))

    If this condition is true, the variable is set to the current bars low.

    ValeurAjustement3PointFibExtension = (Low[0]);

    Here you mention:
    "What i'm trying to do, is that if the low of ValeurAjustement3PointFibExtension is broken, the price will take the new actual low, but the problem, is that, the value is set to the Low[0], and in my mind, since to be trigger, we need to have the price that go below the value of the double, the change in the value will not happen, and stay at the exact low."

    I think that this means you would like to only set ValeurAjustement3PointFibExtension to Low[0] if Low[0] is less than ValeurAjustement3PointFibExtension. Is this correct?

    For example
    Code:
    if (Low[0] < ValeurAjustement3PointFibExtension)
    {
    ValeurAjustement3PointFibExtension = Low[0];
    }
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Thanks !
      This is correct ! I'm trying now, i'm just wandering, i'm not an expert in C++, but in c++ its the first line of code that will be calculated, then right to left, then the next one, etc. So, in your example, the Low[0] of the first line, will be processed before the change of the double into the new Low[0], so its not going to make the matrice explode ?
      Thanks again so much (i have spend hours on this problem and around 100 tabs open right now)

      Comment


        #4
        Hello Robinson94,

        As a tip, NinjaScript is written in C#. There are some small differences but for purposes of scripting its a bit easier to use. (no memory management such as required with C++)

        With C# all code is in methods. When the method is triggered the code is run from top to bottom. If something is started in a new thread, that becomes its own process and is run asynchronously.

        Each time a bar closes, NinjaTrader is updating information about that bar behind the scenes. The Low variable contains a collection of lows for every bar on the chart accessed with a barsAgo value. Low[0] represents the most recent bar's low.


        If the Low[0] is called from OnBarUpdate which is triggered anytime the bar updates, that Low is guaranteed to exist for the series that is updated in that BarsInProgress. (Phrased this way as there can be multiple series added to a single script that both cause OnBarUpdate to trigger. The Low[0] for one may be updated while the Low[0] for another is not.)

        The condition will check the value of ValeurAjustement3PointFibExtension.

        This needs to be set before it is checked to prevent an error. This appears to be set for each historical bar before this code would be checked.

        I noticed a very big mistake in the code as I was about to copy and paste where ValeurAjustement3PointFibExtension is being set in historical data.

        Please notice you have a semicolon after an if statement.

        Code:
        if (State == State.Historical)[B][COLOR="DarkRed"][SIZE="4"];[/SIZE][/COLOR][/B] <---
        {
        ValeurAjustement3PointFibExtension = (Valeur3PointFibExtension);
        Remove this semicolon as semicolons cannot be placed after if statements.
        Code:
        if (State == State.Historical)
        {
        ValeurAjustement3PointFibExtension = Valeur3PointFibExtension;
        
        Draw.FibonacciExtensions(this, @"FibAutoTrailStoplongshortFibonacci extensions_1", false, 0, Valeur1PointFibExtension, 0, Valeur2PointFibExtension, 0, Valeur3PointFibExtension);
        }
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          Thanks for pointing the error !
          I just have 2 questions about the script and strategy.
          I have modify the logic of the script a bit, the fibs extensions are working now, but i have troubles with getting the value of the fib level, and then, creating an order, that is not a strategy order (since what i'm looking for, is manual entry, and then the script handle the exit), but i have tried to create ATM order in the strategy, i only get error, and i have read about some Account order, is this still a thing in NT8, to be enable to have an order, that is not in the strategy (because if i have an order in the strategy that will try to go short to exit a long entered manually, i will have a short and a long..), but that affect all the others positions and orders.

          First, for anybody that try to create a script like this, here's the logic that make the thing work :

          protected override void OnBarUpdate()
          {
          // Fib Extension tracé de base pour avoir une idée de la target avant que la vrai extension soit faites
          if ((AjustementFib == false)
          // Variable étant sur false de base
          && (State == State.Historical))
          {
          ValeurAjustement3PointFibExtension = Valeur3PointFibExtension;
          //Donne la bonne valeur a la variable utiliser pour la vrai extension.
          Draw.FibonacciExtensions(this, @"FibAutoTrailStoplongshortFibonacci extensions_1", false, 0, Valeur1PointFibExtension, 0, Valeur2PointFibExtension, 0, Valeur3PointFibExtension);
          }
          // Si long, et que le troisième point de l'extension est plus basse que le deuxième, et que le troisième point est casser vers le bas, le troisième point continueras d'être changer sur le nouveau low après sa cassure.
          if ((PositionAccount.MarketPosition == MarketPosition.Long)
          && (Low[0] < Valeur3PointFibExtension)
          && (AjustementFib = false))
          {
          AjustementFib = true;
          //Met la varible sur true, et ne peut plus être activé vu que la varible n'est plus sur false
          }
          if ((PositionAccount.MarketPosition == MarketPosition.Long)
          && (AjustementFib == true)
          //Ne peut être activé que si la varible est sur true
          && (Low[0] < ValeurAjustement3PointFibExtension))
          //Si le low casse le niveau de low utilisé pour l'extension
          {
          ValeurAjustement3PointFibExtension = Low[0];
          //le low vas s'ajuster sur le nouveau low, tout comme l'extension plus bas.
          if ( CurrentBar < 1)return;
          PlaySound(NinjaTrader.Core.Globals.InstallDir + @"\sounds\Alert1.wav");
          //Just to check that everything is working, going to be deleted
          RemoveDrawObject("FibAutoTrailStoplongshortFibonac ci extensions_1");
          //Supprime l'ancienne extension avec le troisième point sur Valeur3PointFibExtension
          Draw.FibonacciExtensions(this, @"FibAutoTrailStoplongshortFibonacciAjustement extensions_1", false, 0, Valeur1PointFibExtension, 0, Valeur2PointFibExtension, 0, ValeurAjustement3PointFibExtension);
          //Crée la nouvelle extension avec le troisième point sur ValeurAjustement3PointFibExtension

          if (Close[0] - 5 == (Close[0]))
          {
          if (State < State.Realtime)
          return;
          //Just some junks that is here from when i try to continue the script
          }
          }

          All the script has comments on how it work in french, you can use google translate if you need the comments.

          So, what i'm trying to do now, is first, to get the value of a fib level in the extension, i didn't understand and succeed to make work the PriceLevel logic (https://ninjatrader.com/support/help...ricelevels.htm). And i can't simply do a Close[0] ==(or >=) "ValeurAjustement3PointFibExtension". Because the fib is a string. I was also trying to put an offset, but i don't matters.
          So, i tried to have a variable, that take the value of ValeurAjustement3PointFibExtension (i have put only one fib level to the default extension), but i could not, because i need to find the value of a level of a fib level to put a value to the variable, and i could not make work the pricelevel logic. (By the way, is there a way to create a fib with a certain template, and not the default template ?)
          So, how can i find a way, to see if the price has hit (with an offset or not), the fib level ?

          Then, i tried to create an order, that would have been supposed to get created when the fib level is hit, and that would have been move to the value of an indicator at every bar close, but i already could not create the order like explained in the start of this post.
          So, my second question is, how can i create an order that will be managed by the strategy, but that will flatten my account when filled, even if the entry in my account has not been triggered by the strategy, but manually ?

          Have a great day !

          Comment


            #6
            Hello Robinson94,

            I'm not able to understand.

            Can you simply state the issue?

            Are you printing a variable and getting an unexpected value?

            Are you unsure of how to use a variable to supply a price to an Atm Strategy Method?

            Are you unsure of how to place a trade using Atm Strategy methods?
            Chelsea B.NinjaTrader Customer Service

            Comment


              #7
              Its in did not really clear, the issues are :

              - I can't find the fibonacci level of the extension, to be enable, to do that if the price go above the level, the target, and trailing stop part of the strategy to start. I don't find a way to find a fib level price (i tried the price level logic), to for example, take the value of the fib level, to store it in a variable, and then ask the strategy, to check if the price go above the variable (since i don't think i can simply ask the strategy to see if the price go above the fib level since the extension is a string).

              - Second issue, i don't find a way, to create an order, that can be managed by the strategy, and not being a strategy order. I explain, i enter the trade using a basic atm strategy with the dom, the entry and stop loss are set using a atm strategy, but what i'm trying to do, is that when the price will hit the fib level, the strategy will create a sell stop market order, to trail stop the trade, but i need to create a type of order, that can flatten the account, and the atm strategy, when its filled. So not an order, that will have 1 short handle by the strategy, and 1 long by the atm strategy, when i just want to flatten the account.
              A little bit like the (PositionAccount.MarketPosition == MarketPosition.Long) code, that don't care if the position has been made by a strategy, or manually. But i'm trying to make an order like this, and the ATM order, give me a error that they don't exist in this context, and i didn't find anything about the Account Position for NT8, i only find about this in NT7.

              So, is there a way to make those two things possible ?
              Thanks a lot !

              Comment


                #8
                Hello Robinson94,

                You can loop through the levels of a Fibonacci drawing object and get the prices of these levels.

                For example:
                Code:
                FibonacciExtensions fib = Draw.FibonacciExtensions(this, "fib", true, 15, Close[5] - 5 * TickSize, 10, Close[5] + 5 * TickSize, 5, Close[5]);
                foreach (PriceLevel level in fib.PriceLevels)
                {
                	Print(string.Format("{0} | {1}", level.Value, level.GetPrice(Close[5], Math.Abs(fib.StartAnchor.Price - fib.EndAnchor.Price), false) ));
                }
                Regarding placing managing orders that do not affect the strategy position, you can do this with Atm Strategy methods.


                Or you can use the Account methods from the Addon class.
                Chelsea B.NinjaTrader Customer Service

                Comment


                  #9
                  Thanks about the Print,
                  just, when i have the print :
                  foreach (PriceLevel level in fib.PriceLevels)
                  {
                  Print(string.Format("{0} | {1}", level.Value, level.GetPrice(Close[0], Math.Abs(fib.StartAnchor.Price - fib.EndAnchor.Price), false) ));
                  }

                  How do i do, if i want to put the value that the print will create to a double ?
                  Also, what do those codes :
                  ("{0} | {1}", level.Value, level.GetPrice(Close[0], Math.Abs(fib.StartAnchor.Price - fib.EndAnchor.Price), false ) ));
                  means ? I have also change the Close[5] to Close[0], because the Close[5] was giving an error, and said that there were only 4 bar loaded, when there was a lot more, its not important ? (sorry to ask, but since i dont know how this piece of code work..)

                  And, when i create the fib extension, can i choose to create the extension with a template that is not the default one ?
                  Thanks !

                  Comment


                    #10
                    Hello Robinson94,

                    Brackets indicate an index in an array or collection.

                    When calling Close[5] I'm specifying the close of the bar 5 bars ago.
                    Close[barsAgo index]


                    While I was typing this up, I was drawing the object on the last historical bar. (As it wouldn't make sense to draw this when there is only one bar)

                    I would recommend that you also wait until there are a few bars on the chart before drawing the object.

                    if (CurrentBar < 5)
                    return;


                    I am not able to understand when you ask "How do i do, if i want to put the value that the print will create to a double".
                    Can you clarify your inquiry?

                    level.GetPrice() returns a double.

                    The code you are referring to is a print.
                    To understand why the script is behaving as it is, it is necessary to add prints to the script that print the values used for the logic of the script to understand how the script is evaluating.
                    Dive into manipulating C# code from within an unlocked NinjaScript strategy using the NinjaScript Editor.3:11 Creating a New NinjaScript Strategy13:52 Analyz...


                    I'm printing the level.Value which is the number for that level, and also I'm printing level.GetPrice().

                    level.GetPrice(double startPrice, double totalPriceRange, bool isInverted)
                    Chelsea B.NinjaTrader Customer Service

                    Comment


                      #11
                      Thanks for the video and the links ! The print and the outputs are working now.
                      And my question, that i still have, is now that i have an output that i can see on the NinjaScript Output window (example : 85,4 | 46,43744), how can i do, to turn this into a double, that will not be stored in the NinjaScript output window, but in a double in the NinjaScript strategy, so i can do :

                      mycooldouble = the_output_made_by_the_print(the numbers after the |, only if the numbers before the | are 85,4)
                      since a double and a string are not "compatible", is it possible, to ask the double, to wait for the specified message, like, if the output is :
                      if script_see_this_output
                      85,4 (//the script know this is the fib level)
                      script_will_take_the_value_after_the_|(which is //46,43744 in the example) and set this value as the value of a private double like ValueFib
                      So i can them use this double, has a target price.

                      Thanks !

                      Comment


                        #12
                        Hello Robinson94,

                        level.GetPrice() returns a double.

                        private double myDouble;

                        myDouble = level.GetPrice(Close[0], Math.Abs(fib.StartAnchor.Price - fib.EndAnchor.Price), false);

                        This would fall under general C# education and is not specific to NinjaScript.

                        Below is a publicly available link to an educational site on double.
                        Use the double type to store large numbers with fractional values. Double is an 8-byte number.
                        Chelsea B.NinjaTrader Customer Service

                        Comment


                          #13
                          Hello !

                          Thanks for the clear explains, the order, and the fib level are working, i have been enable to set the value of a double to my dynamic fib level.
                          But i have a problem, with comparing the value of a double with my fib level, to the Close[0], i would be great if you could help me. So, now that i have the double with the fib level that is used as a target price, i can ask the script to wait until the Close[0] is above or egal to the target price, the piece of code compacted is this :

                          Code:
                          if ((Close[0] - 5)  >= ValeurFib)
                          And weirdly enough, the if don't work, i have set a print to the double ValeurFib, the value is good and dynamic to the price level of the fib (example of the value : 46,4716), but when the Close[0] with the offset, is equal or superior to the value of ValeurFib, nothing happen. I have tried to do this in a another script like this :

                          Code:
                          		private double Closevalue;
                          		private double Eddzad;
                          				Eddzad					= 46.5;
                          				Closevalue 				= -1;
                          			Closevalue = Close[0];
                          			if (Instrument.MasterInstrument.Compare(Closevalue, Close[0]) == Eddzad)
                          			{
                          			Print("Bonjour");
                          			}
                          But in this case, the print is trigerred permanently.

                          Here's the full piece of code in the main script, that don't work, but only the line if ((Close[0] - 5) >= ValeurFib), don't work, since i have tried deleting just this line and everything work, and by keeping only this line, nothing work.

                          Code:
                          			if (CurrentBar < 1)return;
                          				Print (ValeurFib);
                          				if (((Close[0] - 5)  >= ValeurFib)
                          				&& (PositionAccount.MarketPosition == MarketPosition.Long)
                          				&& (creationstop == false)
                          				&& (checketape3 == true)
                          				&& (State == State.Realtime))
                          			{
                          				atmtrailstop = GetAtmStrategyUniqueId();
                                			ordretrailstop = GetAtmStrategyUniqueId();
                          			AtmStrategyCreate(OrderAction.Sell, OrderType.StopMarket, -1, -1, TimeInForce.Day, ordretrailstop, "autotrailstop", atmtrailstop, (atmCallbackErrorCode, atmCallbackId) => {
                          			     // checks that the call back is returned for the current atmStrategyId stored
                                   		 if (atmCallbackId == atmtrailstop)
                                    	{
                                       	 // check the atm call back for any error codes
                                       	 if (atmCallbackErrorCode == Cbi.ErrorCode.NoError)
                                      {
                                            // if no error, set private bool to true to indicate the atm strategy is created
                                          creationstop = true;
                          			} 
                          		}
                          	 });
                          				trailstop = true;
                          				Print("Etape 4 ok");
                          }
                          Also, i have an error with the strategy from time to time, i don't know if its related, and its not really documented, but the error don't cancel the strategy. I'm testing the script on historical replay data, it may cause the error ?

                          Strategy 'FibAutoTrailStoplongshort': Error on calling 'OnBarUpdate" method on bar 1: Object reference not set to an instance of an object

                          Have a great day !

                          Comment


                            #14
                            Hello Robinson94,

                            Print the values you are comparing.

                            Print(string.Format("(Close[0] - 5): {0} >= ValeurFib: {1}", (Close[0] - 5), ValeurFib));

                            What does this print?

                            Currenty you are checking that the close of the current bar minus 5 points. (On the ES each point is 4 ticks. This would be a 20 tick distance)
                            Chelsea B.NinjaTrader Customer Service

                            Comment


                              #15
                              Hello again !

                              Thanks ! I didn't realised that i had an offset of 5 points instead of 5 ticks !

                              The hit of the target level work and do create an order now, i have put the price of creation of the order of -1 for a sell stop, and +99999999 for a buy stop, so i don't get hit, is there a way to say have an order, that cannot be filled, so the order cannot be filled after is creation, but after the adjustment of the order, he is enable to get filled.

                              And, i have a problem with the name of the order, where i could really need some help

                              So, i can create my order like this :
                              Code:
                              				atmtrailstop = GetAtmStrategyUniqueId();
                                    			ordretrailstoplong = GetAtmStrategyUniqueId();
                              			AtmStrategyCreate(OrderAction.Sell, OrderType.StopMarket, -1, -1, TimeInForce.Day, "ordretrailstoplong", "atmtrailstop", atmtrailstop, (atmCallbackErrorCode, atmCallbackId) => {
                              And then, what i'm trying to do, is change the value of the stop, with the changestoptarget method, like this : (PS : LONGautotrailstop1, is a value made by the value of an indicator in state loaded, and i want to put my order to the value of this indicator with an offset of 0.01)
                              Code:
                              				AtmStrategyChangeStopTarget(0, LONGautotrailstop1[0], "ordretrailstoplong", atmtrailstop);
                              But, i get the error : "AtmStrategyChangeStopTarget" method error: Order name 'ordretrailstoplong' is invalid
                              Probably because i didn't setup the name of the order in the AtmStrategyCreate well, i have tried a few things, but didn't find how to make work this.
                              So, how can i create a order with AtmStrategyCreate, and then get the specific name of this order, to use it in a AtmStrategyChangeStopTarget ?

                              Thanks !

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by ghoul, Today, 06:02 PM
                              1 response
                              10 views
                              0 likes
                              Last Post NinjaTrader_Manfred  
                              Started by jeronymite, 04-12-2024, 04:26 PM
                              3 responses
                              44 views
                              0 likes
                              Last Post jeronymite  
                              Started by Barry Milan, Yesterday, 10:35 PM
                              7 responses
                              20 views
                              0 likes
                              Last Post NinjaTrader_Manfred  
                              Started by AttiM, 02-14-2024, 05:20 PM
                              10 responses
                              180 views
                              0 likes
                              Last Post jeronymite  
                              Started by DanielSanMartin, Yesterday, 02:37 PM
                              2 responses
                              13 views
                              0 likes
                              Last Post DanielSanMartin  
                              Working...
                              X