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

Position.MarketPosition Clarification

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

    Position.MarketPosition Clarification

    Can somebody please confirm whether or not my understanding of how Position.MarketPosition works by reviewing the example below. I need to know if this sample strategy will send out long market orders on a stochastic cross above 80 when there is no market position on and send out a short order on a stochastic cross below 20 when the account is flat. Then once that position is on it will set a profit target and a stop target based on a double value obtained by using min/max bars back from the close of the bar that sent out the entry order. The entry order, profit target, and stop loss all need to go out during the same onbarupdate call. I will not be using this strategy. It was created simply to verify whether or not I understand how this works. If my code is doing something else please recommend how to fix it.

    ************************************************** ****

    protected override void OnBarUpdate()
    {


    if(CurrentBar < BarsRequiredToTrade) return;



    if(BarsInProgress == 0)
    {

    double bullStop = 0;
    double bearStop = 0;
    double bullTarget = 0;
    double bearTarget = 0;


    if(Position.MarketPosition == MarketPosition.Flat)
    {
    if(CrossAbove(StochasticsFast(3, 14).D, 80, 1))
    {
    EnterLong(DefaultQuantity, "BULL TRIGGER");
    bullStop = MIN(Low, 5)[0];
    bullTarget = MAX(High, 30)[0];
    }

    else if(CrossBelow(StochasticsFast(3, 14).D, 20, 1))
    {
    EnterShort(DefaultQuantity, "BEAR TRIGGER");
    bearStop = MAX(High, 5)[0];
    bearTarget = MIN(Low, 30)[0];
    }
    }


    if(Position.MarketPosition == MarketPosition.Long)
    {
    SetProfitTarget(@"BULL TRIGGER", CalculationMode.Price, bullTarget);

    SetStopLoss(@"BULL TRIGGER", CalculationMode.Price, bullStop, false);
    }

    if(Position.MarketPosition == MarketPosition.Short)
    {
    SetProfitTarget(@"BEAR TRIGGER", CalculationMode.Price, bearTarget);

    SetStopLoss(@"BEAR TRIGGER", CalculationMode.Price, bearStop, false);
    }


    }







    ************************************************** *****
    Last edited by gordongekko; 02-01-2018, 03:29 PM.

    #2
    Hello gordongekko,

    Thank you for your note.

    Trying to submit your stop loss and profit target on the same bar as your entry would not be suggested. The reason for this, is the entry order needs to be submitted to the broker/exchange, filled, and returned to NinjaTrader by the time your StopLoss and ProfiTarget calls are made. So its likley NinjaTrader will not see you in a position and thus not submit your SL and PT on that specific OnBarUpdate.

    You should submit your PT and SL in either State.Configure or OnOrderUpdate, see the following example,


    Please let us know if you need further assistance.
    Alan P.NinjaTrader Customer Service

    Comment


      #3
      Hi Alan,

      Thanks for the response. So what you're saying is that stop loss and profit target orders can't be submitted when flat? So with the above code I posted earlier it is trying to send out the stop and target within a millisecond (basically simultaneously) of submitting the entry order and thus the entry order wont be filled fast enough for it to be live when the stop and target are submitted via the same method.

      That code doesn't work correctly after a historical backtest. I got another test strategy working using the stops in the state.configure but those are too primitive for the majority of the strategies I want to use. None of my systems use arbitrary stops based on some static tick amount or % change in price which is why I don't think it's possible to use the basic state.configure stops because I need the price target and stops to be price points assigned to doubles form data obtained via methods that wont run until after barsinprogress == x. That being the case is OnOrderUpdate the only way for me to do this because if i use: SetStopLoss(@"BULL TRIGGER", CalculationMode.Price, bullStop, false) it wont know the value assigned to the double bullStop so it will have to be some number I assign when creating the variable since it can't get the actual data i want assigned to it until later.

      I just need to know how to reference the data once the order is filled so the profit target and stop orders are sent out correctly. Isn't it possible to have the stop and target go out on the same on bar update when using a price point assigned to the stop code (i.e bullStop = Low[5]) when the trigger bar closes?
      Last edited by gordongekko; 02-01-2018, 05:48 PM.

      Comment


        #4
        SetStopLoss and SetProfitTarget should be coded before the entry. They are submitted as soon as the entry order is executed as long as the entryName of all three is the same.

        Comment


          #5
          Hello gordongekko,

          Thank you for your response.

          To submit the Stop Loss and Profit Target when the entry fills use OnExecutionUpdate(): https://ninjatrader.com/support/help...tionupdate.htm
          Make sure you assign the values you wish in the same condition as your entry just like you did in your original post.

          Another option if you were set on submission of Profit Target and Stop Loss at the same time you submit the entry order is to use the Unmanaged Order Approach which will allow you to submit orders without the protective logic of the Managed Order Approach. However, that means Unmanaged Order Approach involves much more programming and handling of orders and positions.
          If you want to learn more about the Unmanaged Order Approach please visit the following link: https://ninjatrader.com/support/help...d_approach.htm

          Please let me know if you have any questions.

          Comment


            #6
            Hi Patrick,

            That worked. Thanks for providing an actual solution. I'm still getting some errors but the orders are going out correctly. How do I change this to submit a market if touched order for the profit target?

            SetStopLoss(@"BULL TRIGGER", CalculationMode.Price, bullStop, false);

            This is sending out a stop limit order for the profit target. I found the syntax for ExitLongMIT() but can I do this using the setstoploss?
            Last edited by gordongekko; 02-02-2018, 10:08 AM.

            Comment


              #7
              Hello gordongekko,

              Thank you for your response.

              SetStopLoss will only be Stop Market orders in NinjaTrader 8. There is no option to change it's order type.

              Please let me know if you have any questions.

              Comment


                #8
                I redid the test system I posted in the original question using OnExecutionUpdate() for the stop and target orders. It works perfectly except that I'm getting order id cannot be reused errors that are causing the strategy to self-terminate. Do you have any ideas on what could be causing that?

                Comment


                  #9
                  Hello gordongekko,

                  Thank you for your response.

                  Please provide the full error detail and your OnExecutionUpdate() code.

                  Comment


                    #10
                    The error in the log is:

                    2018-02-02 08:50:19:375|0|4|Strategy 'MACD LINE CROSS BOT OEU/127247954' submitted an order that generated the following error 'Order rejected'. Strategy has sent cancel requests, attempted to close the position and terminated itself.
                    2018-02-02 08:50:19:375|1|4|Disabling NinjaScript strategy 'MACD LINE CROSS BOT OEU/127247954'


                    The stop portion of the code is:


                    protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
                    {

                    if (execution.Order.Name == "BULL TRIGGER")
                    {
                    SetProfitTarget(@"BULL TRIGGER", CalculationMode.Price, bullTarget);

                    SetStopLoss(@"BULL TRIGGER", CalculationMode.Price, bullStop, false);
                    }

                    if (execution.Order.Name == "BEAR TRIGGER")
                    {
                    SetProfitTarget(@"BEAR TRIGGER", CalculationMode.Price, bearTarget);

                    SetStopLoss(@"BEAR TRIGGER", CalculationMode.Price, bearStop, false);
                    }

                    }

                    Comment


                      #11
                      Hello gordongekko,

                      Thank you for your response.

                      I doubt that the SetStopLoss or SetProfitTarget caused that but I would need to be certain. Can you send me your log and trace files?

                      You can do this by going to the Control Center-> Help-> Mail to Platform Support. Ensuring 'Log and Trace Files' is checked will include these files. This is checked by default.

                      Please place 'ATTN: Patrick H' in the subject line and reference this thread in the body of the email.

                      I look forward to assisting you further.

                      Comment


                        #12
                        I will send those files over if this issue persists with other strategies that I'm actually going to use live but first I need to figure out how to use a stop that goes out onorderexecution like I'm doing now which works as intended but instead of using a profit target I want to use additional exit options that are based on price action/indicator levels, etc that aren't static and thus not know at the time the order is filled like the stoploss point. How do I do this?

                        Here is my sample code. This doesn't compile but you can see what I'm trying to do here. I'm guessing the the non-stop loss exit must be in a different method and can't be in onorderexecution? The part that needs to be moved to another method or accessed another way is in bold. I just need to know how to make this work so that I can have a stop that goes out as soon as the order is filed which it's doing now but have one or more additional exit criteria in place so basically whichever exit is hit first will unload the position.

                        ************************************************** ********

                        protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
                        {

                        if (execution.Order.Name == "BULL TRIGGER")
                        {
                        SetStopLoss(@"BULL TRIGGER", CalculationMode.Price, bullStop, false);

                        if(C1ose[0] < Low[1] && Position.MarketPosition == MarketPosition.Long)
                        {
                        ExitLong(DefaultQuantity,"BULL TRIGGER");
                        }

                        }

                        if (execution.Order.Name == "BEAR TRIGGER")
                        {
                        SetStopLoss(@"BEAR TRIGGER", CalculationMode.Price, bearStop, false);

                        if(Close[0] > High[1] && Position.MarketPosition == MarketPosition.Short)
                        {
                        ExitShort(DefaultQuantity,"BEAR TRIGGER");
                        }

                        }

                        }

                        ************************************************** *******************************
                        Last edited by gordongekko; 02-02-2018, 12:48 PM.

                        Comment


                          #13
                          Hello gordongekko,

                          Thank you for your response.

                          You would need to move those conditions and actions to OnBarUpdate() to have them update on the price data of the bars.

                          Please let me know if you have any questions.

                          Comment


                            #14
                            So basically if you want a stop based on a static level that is known at the time a position is filled you put that in onexecution update and any additional exit conditions that require price data obtained via onbarupdate need to be in that method.
                            Last edited by gordongekko; 02-02-2018, 01:21 PM.

                            Comment


                              #15
                              That is correct, gordongekko.

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by ScottWalsh, Today, 06:52 PM
                              3 responses
                              19 views
                              0 likes
                              Last Post NinjaTrader_Manfred  
                              Started by trilliantrader, Today, 03:01 PM
                              2 responses
                              19 views
                              0 likes
                              Last Post helpwanted  
                              Started by cre8able, Today, 07:24 PM
                              0 responses
                              1 view
                              0 likes
                              Last Post cre8able  
                              Started by Haiasi, Today, 06:53 PM
                              1 response
                              4 views
                              0 likes
                              Last Post NinjaTrader_Manfred  
                              Started by ScottW, Today, 06:09 PM
                              1 response
                              7 views
                              0 likes
                              Last Post NinjaTrader_Manfred  
                              Working...
                              X