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

Price of last order

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

    Price of last order

    Hello, Im trying to code strategy, which enters to position only for example 20 ticks far away of last open position. Coul anybody help me with this?

    #2
    Hello tranta,

    Thank you for your post.

    Below you will find a basic example of this idea.
    Code:
            #region Variables		
    		private bool firstTrade = true;
    		private IOrder entryL = null;
    		private double lastPosPrice = 0;
            #endregion
    
    		
            protected override void Initialize()
            {
    			
            }
    		
    		protected override void OnBarUpdate()
    		{	
    			if(firstTrade && Close[0] > Open[0])
    			{
    				entryL = EnterLong();
    				firstTrade = false;
    			}
    			if(!firstTrade && (Close[0] >= (lastPosPrice + 20*TickSize) || Close[0] <= (lastPosPrice - 20*TickSize)))
    			{
    				entryL = EnterLong();
    			}
    		}
    		
    		protected override void OnOrderUpdate(IOrder order)
    		{
    			if (entryL != null && entryL == order)
    			{
    				if (order.OrderState == OrderState.Filled)
    				{
    					lastPosPrice = order.AvgFillPrice;
    					entryL = null;
    				}
    			}
    		}
    For information on the concepts used in this example please visit the following links:

    Comment


      #3
      Good day, I wrote a code which uses iorder for a long. It enters with filled first order and if market goes against my price, another contract is bought in a variable (Be) number of ticks below previous filled order. It goes again and again until market price reaches average price + profittarget.

      But the code works only when the price of first order of the trade is lower than a price of last order of previous already closed trade. Can u assist me to modify the code to apply also for orders with price higher than previous closed trade filled orders. Thank you

      #region Variables

      // Wizard generated variables

      private int profitTarget = 20; // Default setting for ProfitTarget

      private int be = 20; // Default setting for Be

      private int cciPeriod = 14; // Default setting for CciPeriod

      private int cciValue = -150; // Default setting for CciValue

      private bool firstTrade = true; // Default setting for FirstTrade

      private double lastPosPrice = 0; // Default setting for LastPosTrade

      private IOrder entryLong = null;

      // User defined variables (add any user defined variables below)

      #endregion




      /// <summary>

      /// This method is used to configure the strategy and is called once before any strategy method is called.

      /// </summary>

      protected override void Initialize()

      {

      Add(CCI(CciPeriod));

      SetProfitTarget("Long", CalculationMode.Ticks, ProfitTarget);

      CalculateOnBarClose = true;

      }




      /// <summary>

      /// Called on each bar update event (incoming tick)

      /// </summary>

      protected override void OnBarUpdate()

      { //Condition Set 1

      if (Position.MarketPosition == MarketPosition.Flat)

      {

      SetProfitTarget("Long", CalculationMode.Ticks, ProfitTarget);

      }

      else if (Position.MarketPosition == MarketPosition.Long)

      {

      SetProfitTarget("Long", CalculationMode.Price, Position.AvgPrice + ProfitTarget*TickSize);

      }



      // Condition set 2

      if (FirstTrade && CrossAbove(CCI(CciPeriod), CciValue, 1)

      && Close[0] > Open[0])

      {

      entryLong = EnterLongStop(DefaultQuantity, High[0] + 1 * TickSize, "Long");

      FirstTrade = false;

      }

      if (!FirstTrade && (Close[0]<(LastPosPrice-Be*TickSize)))

      {

      entryLong = EnterLongStop(DefaultQuantity, High[0] + 1 * TickSize, "Long");

      }

      }



      protected override void OnOrderUpdate(IOrder order)

      {

      if (entryLong != null && entryLong == order)

      {

      if (order.OrderState == OrderState.Filled)

      {

      LastPosPrice = order.AvgFillPrice;

      entryLong = null;

      }

      }

      }

      Comment


        #4
        Hello,

        Thanks for the post.

        I don't understand exactly what you are going for? Are you looking to have the opposite that you have coded for the long side occur for short trades? In which case you would just duplicate all your logic for the short side?

        What specifically are you looking for? Can you break down the problem further into a smaller code segment or ask a specific question and I will be happy to assist.

        Comment


          #5
          Hi Brett,

          this code is only for a long side and says, if the first order is filled and ProfitTarget is hit, wait for another CCI signal. If next signal comes, order is filled and price goes in an opposite direction for 50 ticks (variable Be), fill another order lower from first order and set a profit target (for example 10 ticks) over average position price.

          The code works like that only when entry price of order of first trade is higher than entry price of first order of second trade. It does not work when I get CCI signal at a price higher than price of last order of previous trade. The solution must be either in condition set 2 or onorderupdate section as shown below. Thanks a lot for your assistance

          // Condition set 2

          if (FirstTrade && CrossAbove(CCI(CciPeriod), CciValue, 1)

          && Close[0] > Open[0])

          {

          entryLong = EnterLongStop(DefaultQuantity, High[0] + 1 * TickSize, "Long");

          FirstTrade = false;

          }

          if (!FirstTrade && (Close[0]<(LastPosPrice-Be*TickSize)))

          {

          entryLong = EnterLongStop(DefaultQuantity, High[0] + 1 * TickSize, "Long");

          }

          }



          protected override void OnOrderUpdate(IOrder order)

          {

          if (entryLong != null && entryLong == order)

          {

          if (order.OrderState == OrderState.Filled)

          {

          LastPosPrice = order.AvgFillPrice;

          entryLong = null;

          }

          }

          }

          Comment


            #6
            squashfan,

            Would you mind attaching your CS file so that I can further investigate this on my end.
            You can find the file in (My) Documents -> NinjaTrader 7 -> bin -> custom -> Strategy

            Click Reply -> Go Advanced -> Click the paperclip on the top toolbar
            Cal H.NinjaTrader Customer Service

            Comment


              #7
              Hi I send attached code
              Attached Files

              Comment


                #8
                Squashfan,

                I took a look at the code.

                You only have one instance where you are checking the CCI values and that is for the very first trade. After the first trade your first statement in the 2nd condition is no longer going to be true throughout the rest of the code.

                Further more, your second statement is checking the closing price is less than the last order's fill price minus a set ticksize. Which is why you don't see it take at the higher sets.

                You will need to go through your conditions and rework how you want the conditions to work or add in some extra ones.

                Let me know if I can be of further assistance.
                Cal H.NinjaTrader Customer Service

                Comment


                  #9
                  Hi Cal, many thanks for your comment. I will work on it. Have a nice day.

                  Comment


                    #10
                    Hi,
                    find in an attachement a strategy which goes long after CCI signal. If it goes 30 ticks in an opposite direction, it buys another signal and 30 ticks lower another one an so on until actual price hits position average price plus profit target. Problem is when I backtest it, the difference between bought contracts is often closer than 30 ticks. Can you help me where I made a mistake?
                    Attached Files

                    Comment


                      #11
                      squashfan,

                      You are on the right track here, however, I did find instances where your code will place another Long order from the first condition.

                      In the first condition you are placing a Stop Order and then setting the FirstTrade to false.

                      Later on in the same method you reset the variable back to true, cause your position is still flat.

                      You're scenario works only if the stop order gets immediately filled.

                      You could check when all your profit targets are filled in OnExecution and then reset your FirstTrade Variable.
                      Cal H.NinjaTrader Customer Service

                      Comment


                        #12
                        price of last order

                        Hi I try to write a code for a long which adds another contract when price goes 30 ticks against the trade and adds other contract further 30 ticks down until price hits position average price + profit target. But it still adds contracts in less than 30 ticks down. I cannot debug it. Can u assist me?
                        Attached Files

                        Comment


                          #13
                          Squashfan,

                          You are resetting the entryLong to null again when it is filled. Thus your condition is becoming true again for the initial entry on the next OnBarUpdate.

                          Also, you are using the same IOrder and same entry name for entering another position which can cause issues later on.

                          I would recommend resetting the IOrders after your profit targets have been filled so you can reset the table and using different IOrder names and entry names for your other entries.
                          Cal H.NinjaTrader Customer Service

                          Comment


                            #14
                            Good Day

                            I have refined a code for a long with a profittarget. If market goes against the price the code buys another contract 30 ticks lower last filled order until the price reaches position avg. price + profit target. There is a bug in the code I cannot find. Can u direct me?
                            Attached Files

                            Comment


                              #15
                              Squashfan,

                              What is the bug?
                              Is it not moving the Profit target or placing another trade?
                              Cal H.NinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by helpwanted, Today, 03:06 AM
                              1 response
                              12 views
                              0 likes
                              Last Post sarafuenonly123  
                              Started by Brevo, Today, 01:45 AM
                              0 responses
                              9 views
                              0 likes
                              Last Post Brevo
                              by Brevo
                               
                              Started by aussugardefender, Today, 01:07 AM
                              0 responses
                              5 views
                              0 likes
                              Last Post aussugardefender  
                              Started by pvincent, 06-23-2022, 12:53 PM
                              14 responses
                              242 views
                              0 likes
                              Last Post Nyman
                              by Nyman
                               
                              Started by TraderG23, 12-08-2023, 07:56 AM
                              9 responses
                              387 views
                              1 like
                              Last Post Gavini
                              by Gavini
                               
                              Working...
                              X