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

Help using entry price to calculate targets & stops

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

    Help using entry price to calculate targets & stops

    Hi guys

    I'm struggling when trying to use entry price to calculate targets & stops

    Please can you help

    I'm trying to use something like

    Code:
      if (Position.MarketPosition == MarketPosition.Long)
                {
                    SetStopLoss(CalculationMode.Price, Low[2]);
                    SetProfitTarget(CalculationMode.Price, (Position.AveragePrice + (Position.AveragePrice - Low[2])));
                }
    should this go in the else if (State == State.Configure) section? or does this need to by dynamically calculated in the on bar update?

    If I have it in the state.configure section I'm getting the below error in the console, not when building

    Error on calling 'OnStateChange' method: Object reference not set to an instance of an object.

    If I place it in on bar update it's clearly not doing what I want it to

    I also want to use something like

    Code:
    if (Position.MarketPosition == MarketPosition.Short)
                    {
                        SetStopLoss(CalculationMode.Price, Swing(5).SwingHigh[0]);
                        SetProfitTarget(CalculationMode.Price, (Position.AveragePrice - (Position.AveragePrice + Swing(5).SwingHigh[0])));
                    }
    But I'm getting the same problems.

    I think you can see the kind of thing I'm trying to do a previous price value to create a stop & then use that to calculate the target.

    Any help would be great please, I've searched through the forum & found some good posts, just cant get it working sorry

    Thanks
    Gav

    #2
    Hello Gav_G,

    Thanks for your post.

    As you have observed, setting them (profit target, stop target) with price in the state.configure does not work. Typically you would set them in State.Configure if you wanted to use exactly the same values for each order, for example, if you always used a 10 tick stop and always used a 20 tick profit target, this makes coding your strategy easier as you need only code for the entry conditions knowing that the system will provide the 10 tick stop and 20 tick profit targets as soon as the entry order is filled.

    As you are wanting to have a different profit and stop target each time, then you will need to use the Set methods in the OnBarUpdate().

    The thing to keep in mind is that these set method will retain the last value they were set to and these methods place orders as soon as the entry is filled so it is critical that these be set to the correct value before the entry fills. If not set correctly then your strategy will produce an error message likely with a rejected order.

    The recommended practice is to "reset" these after use (when you are flat) to a known value. Another way to do this is to set the values just before you place the entry order. For example:

    if (Your conditions to enter an order)
    {
    SetStopLoss(CalculationMode.Price, Low[2]);
    SetProfitTarget(CalculationMode.Ticks, 20); // start with 20 tick profit target (or whatever higher target you wish based on ticks
    // your entry order goes here
    }

    if (Position.MarketPosition == MarketPosition.Long)
    {
    SetProfitTarget(CalculationMode.Price, (Position.AveragePrice + (Position.AveragePrice - Low[2]))); // adjust profit to this specific price level
    }


    The reason for setting the profit with ticks first is that Position.average price is not yet known. Once the entry order has been filled you can then adjust your profit target to the desired level.

    Note: A potential issue (as I am not sure if this is your intent) with the above profit target is that on each OnBarUpdate the profit target is adjusted because the value of Low[2] will change. If you only want this set once then you would use a bool variable to control setting the profit just once.
    Paul H.NinjaTrader Customer Service

    Comment


      #3
      Awesome thanks so much for the help that is all making sense & I will give that a try now

      Yes I would also need to use a bool variable then, as I want to keep the same stop/target & not adjust after each bar update

      Please could you share some example code of how I might do this? I'm assuming something that states if the current bar is not equal to the bar the position was opened on? if you could provide a simple example of something that is commonly used that would be great though thanks

      Comment


        #4
        Hello Gav_G,

        Thanks for your reply.

        In the area above protected override void OnStateChange() and below public class (name of script) you can create a bool variable like this: private bool doitonce = true; // initialize to true

        Continuing with the previous example:

        if (Your conditions to enter an order)
        {
        SetStopLoss(CalculationMode.Price, Low[2]);
        SetProfitTarget(CalculationMode.Ticks, 20); // start with 20 tick profit target (or whatever higher target you wish based on ticks
        // your entry order goes here
        }

        if (Position.MarketPosition == MarketPosition.Long && doitonce)
        {
        SetProfitTarget(CalculationMode.Price, (Position.AveragePrice + (Position.AveragePrice - Low[2]))); // adjust profit to this specific price level
        doitonce = false; // prevent reentry till a new order.
        }

        if (position.MarketPosition == MarketPosition.Flat)
        {
        doitonce = true; // reset for next order
        }

        Paul H.NinjaTrader Customer Service

        Comment


          #5
          Awesome thanks Paul, that is all making perfects sense

          One other questions please

          I'm also going to want to create some logic that will move stops to break even if the amount of profit has got to 1:1 risk reward ratio

          I think that I'll need to drop this code in.....

          if (Position.MarketPosition == MarketPosition.Long && doitonce)
          {
          SetProfitTarget(CalculationMode.Price, (Position.AveragePrice + (Position.AveragePrice - Low[2]))); // adjust profit to this specific price level
          HERE
          doitonce = false; // prevent reentry till a new order.
          }

          ??

          if you could point me in the direction of any help material to do this I'd be grateful, I'm assuming there is a function that I can ask what is the amount of profit in ticks on that bar close? or will I need to calculate it from Close[0] - Position.AveragePrice??

          Also I'm fine dropping in a sub if in there aren't I?

          Thanks again for all the help, as you can probably see I'm just finding my feet!

          Comment


            #6
            Hello Gav_G,

            Thanks for your reply.

            I'm not aware of any reference materials I could point you to. You will just need to code something up and test it out.

            Certainly comparing the current price to your entry price would be the basis for any adjustment to your stop. You would need to decide if that is a one-time operation or an operation that acts like a trailing stop in that it will only move in one direction and as price moves into profits. A one-time operation would be a candidate for using another bool.
            Paul H.NinjaTrader Customer Service

            Comment


              #7
              Ok super thanks Paul, I am seeing some strange results with the example you have given, with regards to seeing the stop loss though I will post a screen shot now if that's ok?

              Comment


                #8
                This is the code I've written, I'm not sure it is in the right order as I'm seeing some different placements for targets & stops & I think it could be something to do with the order?

                Code:
                        protected override void OnBarUpdate()
                        {
                            //Add your custom strategy logic here.
                
                            if (CurrentBars[0] < BarsRequiredToTrade)
                                return;
                
                            // Long Entry
                
                            if (CrossAbove(EMA1, EMA2, 1))
                            {
                                SetStopLoss(CalculationMode.Price, Low[2]);
                                SetProfitTarget(CalculationMode.Ticks, 200);
                                EnterLong();
                            }
                
                            if (Position.MarketPosition == MarketPosition.Long && first)
                            {
                                SetProfitTarget(CalculationMode.Price, (Position.AveragePrice + (Position.AveragePrice - Low[2])));
                                first = false;
                            }
                
                            if (Position.MarketPosition == MarketPosition.Flat)
                            {
                                first = true;
                            }
                
                                // Short Entry
                                //if (CrossBelow(EMA1, EMA2, 1))
                
                        }
                I've attached a screenshot where you can see what I mean, the targets & stops appear to be different sometimes

                does it need to go to the next bar for the new target calculation to work? I thought it would all happen at the same time?
                Attached Files

                Comment


                  #9
                  Hello Gav_G,

                  Thanks for your reply.

                  At this point, I would like to refer you to our debugging tips as this is where you need to be able to prove what you think the code is doing either with draw objects on the chart (to show when/where) and/or print statements to print to the (new>Ninjascript Output) window values of the variables used.

                  Reference: https://ninjatrader.com/support/help...script_cod.htm

                  The set methods (profit and stop) will be placed as soon as the order is filled. If you are using Calculate.OnBarClose then the entry order is not placed until the end of the bar and would then be filled on the next bar. This would be the same case if you were looking at historical orders as well.

                  I would suggest adding print statements in your entry block to print the actual value of Low[2] and then add a print statement in your block where you are adjusting the profit target to understand the specific values used if this is the area of concern.

                  Debugging is basically the processes of proving your assumptions of what the code is doing, so eliminate the guesswork and prove the code is doing what you expect it to when it is expected to and then adjust as needed.
                  Paul H.NinjaTrader Customer Service

                  Comment


                    #10
                    Great stuff thanks Paul

                    Comment

                    Latest Posts

                    Collapse

                    Topics Statistics Last Post
                    Started by hazylizard, Today, 08:38 AM
                    2 responses
                    8 views
                    0 likes
                    Last Post hazylizard  
                    Started by geddyisodin, Today, 05:20 AM
                    2 responses
                    17 views
                    0 likes
                    Last Post geddyisodin  
                    Started by Max238, Today, 01:28 AM
                    5 responses
                    46 views
                    0 likes
                    Last Post Max238
                    by Max238
                     
                    Started by giulyko00, Yesterday, 12:03 PM
                    3 responses
                    13 views
                    0 likes
                    Last Post NinjaTrader_BrandonH  
                    Started by habeebft, Today, 07:27 AM
                    1 response
                    16 views
                    0 likes
                    Last Post NinjaTrader_ChristopherS  
                    Working...
                    X