Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Reverse Position at Trail stop hit or trigger

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

    Reverse Position at Trail stop hit or trigger

    Dear Sir or Madam

    I used the automated system Ninja Scripts to create a strategy of two sets, one for long position and the other for the short that works as I want, however As soon as one of the two position hits the stop loss I want them to be reversed automatically so they continue with the trend movement.
    the opened position after trail stop hit will be with the same conditions (trailing stop loss 4 ticks and no Take profit because it will be stopped automatically by my strategy later.)
    Please note, that I looked over all the Ninjatrader forum pages, internet, futures.iso web.. everything. the best I came with is an on-execution code which I am attaching with this post.
    I do not understand I found this post subject since 2009, and the same problem asked by many people and no one has like a straight clear answer step by step to it.
    I need the method on how to Reverse my position after trail stop/stop-loss is trigger or hit. if the code I attached is the right solution I need to understand how to connect it with the strategy İ have created step by step since I am not a pro-programmer, I will need to link two codes with basic knowledge of C#, if not, please explain to me step by step how to do it. I will be very grateful, and I believe the forum will be also due to the number of people I saw them asking.
    Please
    Attached Files
    Last edited by Yassine.Chetouani; 05-16-2016, 07:15 AM.

    #2
    Hello Yassine.Chetouani,

    Thanks for your post and welcome to the forums!

    I see that you have made a similar post in another thread and I will answer that post by linking it to this post so that you have the one answer in two places.

    To reverse your position after trail stop or stop loss is hit will require code that detects that either has been hit and then code that then enters an order in the desired direction.

    For the detection of an order execution you can look for the order name of Trail stop or Stop loss in OnExecution()

    Here is an example of code that detects and prints what the order is:

    Code:
    protected override void OnExecution(IExecution execution)
    		{
        		    if (execution.Name == "Stop loss")
             	      Print(string.Format("{0} - Stop loss was filled", execution.Time));
    			
    		    if (execution.Name == "Trail stop")
    		      Print(string.Format("{0} - Trail stop was filled", execution.Time));	
    		}
    You can use the above code to test the detection out as it will send the print statements to the output window (Tools>output window).

    With the above code you can then add logic to your code to then enter an opposite direction order.

    Note: We recommend that you (edit) remove your e-mail address and phone from your post as there are bots that will collect and use that information.
    Paul H.NinjaTrader Customer Service

    Comment


      #3
      Dear Sir or Madam,

      I want to inform you that the Trail stop or Stop loss reverse issues was successfully solved after the help given by Mr.Paul, So thank you again.

      Now I have an other issue that it seems not to find a direct answer even after trying several methods and reading & executing previous posts solution from your forum.

      What I want while I am using Renko or Range bars, I would like the strategy to look back 5 bars the moment it enters a trade, and put the stop loss 1 tick below the lowest close of the last 5 bars in case of long entry and Highest of the close of the previous 5 bars in case of Short entry. I don't want it to look back 5 bars every new bar after the entry bar and adjust the stoploss.

      I tried this, but unfortunately it didn't work.
      CODE:


      if (Position.MarketPosition == MarketPosition.Long)
      {
      SetStopLoss(CalculationMode.Price, LowestBar(Close,5.BarsSinceEntry())-1*TickSize);
      }

      if (Position.MarketPosition == MarketPosition.Short)
      {
      SetStopLoss(CalculationMode.Price, HighestBar(Close,5.BarsSinceEntry()+1*TickSize));
      }

      Please, Can you help me with this part, I saw there is also a MAX and MIN commands.

      MIN(Low, 5)[0] - 1 * TickSize
      or
      MAX(High, 5)[0] + 1 * TickSize

      however I believe they update the stop loss on each bar entry,

      Besides,
      After solving this one. I want the Stop loss to be updated to breakeven after 30 ticks profits
      So I believe adding this code will make it function perfectly.


      // Resets the stop loss to the original value when all positions are closed
      if (Position.MarketPosition == MarketPosition.Flat)
      {
      SetStopLoss(CalculationMode.Ticks, StopLoss);
      }
      // If a long position is open, allow for stop loss modification to breakeven

      else if (Position.MarketPosition == MarketPosition.Long)
      {
      // Once the price is greater than entry price+30 ticks, set stop loss to breakeven
      if (Close[0] > Position.AvgPrice + 30 * TickSize)
      {
      SetStopLoss(CalculationMode.Price, Position.AvgPrice);
      }
      }
      else if (Position.MarketPosition == MarketPosition.Short)
      {
      // Once the price is less than price+30 ticks, set stop loss to breakeven
      if (Close[0] < Position.AvgPrice - 30 * TickSize)
      {
      SetStopLoss(CalculationMode.Price, Position.AvgPrice);
      }


      Please Feel free to add or inform me about any errors that may occur while adding this 3th part of my stop loss conditions also.

      I will be very glad to hear from you soon.
      Thank you for your help in advance.

      Comment


        #4
        Hello Yassine.Chetouani,

        Thanks for your post.

        If you have something that you only want to happen once, such as setting a particular stop level then you would need to use bool variables that you declare, initialize and set as needed to control the flow of the program.

        For example in the regions variables you might declare a bool like: private bool doitonce = true;

        Then in the OnBarUpdate() section of the code you would use it like:

        if (some condition && doitonce)
        {
        // execute some action here
        doitonce = false; // set to false so action only done once
        }

        Later in your code you would need to determine some other condition where you would want to reset the bool back to true, here is an example:

        if (Position.MarketPosition == MarketPosition.Flat)
        {
        doitonce = true; // reset to true for next entry into market
        }

        I think you had the right idea to use the Min and Max methods so if you combine that with the use of a bool you will set the stop and set it just the once. For example:

        if (Position.MarketPosition == MarketPosition.Long && doitonce)
        {
        SetStopLoss(CalculationMode.Price,MIN(Low, 5)[0] - 1 * TickSize );
        Print ("stop set at: "+(MIN(Low, 5)[0] - 1 * TickSize)); // print to output window stop used
        doitonce = false; // prevent further adjustment
        }

        // don't forget to reset the bool doitonce when flat!!!

        Your code example for setting to breakeven looks fine. If you want you can also implement another bool so that the statement to move the stop to breakeven is only done once..
        Paul H.NinjaTrader Customer Service

        Comment


          #5
          Dear Sir Mr.Paul,

          First of all thank you for giving your time answering me. and I really mean it Sir, many thanks.
          Sorry for the disturb again but I still need your knowledge sharing on this subject

          2- The strategies that I created till now were with RSI/SMA/Stoch... however with market divergence problem. some entries. doesn't give profit even if the indicators show a possible profit since the market is on the divergence if you see what I mean.
          So I tried manually this system on candle patterns, it worked with small profit

          Now Mr.Paul, I hope if you can help me with this indicator error. the indicator is so complicated that I couldn't create one condition nor simply added it on the chart as a strategy part in void Initialize() . So can you help me to detect where I made the mistake here. I am attaching the Code I tried to create and the error given as picture with this mail.

          I can send you the indicator or any details if you need.
          If I can do just one condition by solving this error of the Evening Star (as example), I believe I will do all the other 25 conditions ı want + I can add the stop loss conditions since I learned now how to do it.

          Thank you Sir.
          I will be waiting for your comment impatiently
          Eng.Yassine Chetouani

          Attached Files

          Comment


            #6
            Hello Yassine.Chetouani,

            Thanks for your post.

            Please note that your post is not related to the thread topic, " Reverse Position at Trail stop hit or trigger" nor is it related to the forum thread of "Strategy Analyzer". I will of course answer your question but any future questions you have should be placed in the appropriate forum and should relate to the thread topic (or start a new thread). This helps us keep the forum better organized and benefits all users by keep the posts related based on searches. Thanks in advance for your cooperation.

            What I suggest, to debug the issue, is to use the indicator itself to identify the patterns on the chart. IE apply the indicator to the chart and set the indicator to identify the candle pattern you seek in the strategy. Then use the strategy with the very same pattern check and have the strategy place a dot above the candlestick pattern. In this way you see the correct functionality of the indicator by itself and then confirmation of your strategy that it is also accessing the same information. I would also recommend, for testing purposes, to use a very common pattern such as a bearish or bullish engulfing so that you can see it is working.

            I don't have the 3rd party indicator you reference however it appears very similar to the NinjaTrader indicator CandleStickPattern. I've created a simple test strategy and applied it and the CandleStickPattern indicator to the same chart to show you what you should expect to see. The indicator colors the bar and adds the text to the chart whilst the strategy places a red dot above the candle where the pattern was detected. Please see attached.
            Attached Files
            Paul H.NinjaTrader Customer Service

            Comment


              #7
              Dear Mr.Paul

              I want to thank you for answering me earlier and I want to inform you that I opened a new tread under this link.



              My apologies again
              Thanks.

              Comment


                #8
                Originally posted by NinjaTrader_PaulH View Post
                Hello Yassine.Chetouani,

                Thanks for your post and welcome to the forums!

                I see that you have made a similar post in another thread and I will answer that post by linking it to this post so that you have the one answer in two places.

                To reverse your position after trail stop or stop loss is hit will require code that detects that either has been hit and then code that then enters an order in the desired direction.

                For the detection of an order execution you can look for the order name of Trail stop or Stop loss in OnExecution()

                Here is an example of code that detects and prints what the order is:

                Code:
                protected override void OnExecution(IExecution execution)
                {
                if (execution.Name == "Stop loss")
                Print(string.Format("{0} - Stop loss was filled", execution.Time));
                
                if (execution.Name == "Trail stop")
                Print(string.Format("{0} - Trail stop was filled", execution.Time));
                }
                You can use the above code to test the detection out as it will send the print statements to the output window (Tools>output window).

                With the above code you can then add logic to your code to then enter an opposite direction order.

                Note: We recommend that you (edit) remove your e-mail address and phone from your post as there are bots that will collect and use that information.
                Paul would you be able to expand upon the "THEN" portion of this coding? I understand up to the point of setting the trailing stop and when its triggered, to capture that though the "OnExecution" script above, but what would the script look like to then place a reversal order? Thanks in advance

                Comment


                  #9
                  Hello joshmock89,

                  You could check execution.MarketPosition to see if it was a Long (Buy) or Short (Sell) execution.

                  If you include a bool in your logic to allow reversals, handling a reversal could look like the following if you want to use OnExecution:

                  Code:
                  private bool MyAllowReversalBool = true;
                  
                  protected override void OnExecution(IExecution execution)
                  {
                      if (execution.Name == "Stop loss" && execution.MarketPosition == MarketPosition.Short && MyAllowReversalBool == true)
                      {
                          // This is a Sell Execution for a stop loss, call EnterShort to enter a short position.
                          EnterShort();
                          // If we want to turn reversals off:
                          MyAllowReversalBool = false;
                      }
                  }
                  JimNinjaTrader Customer Service

                  Comment

                  Latest Posts

                  Collapse

                  Topics Statistics Last Post
                  Started by bortz, 11-06-2023, 08:04 AM
                  47 responses
                  1,610 views
                  0 likes
                  Last Post aligator  
                  Started by jaybedreamin, Today, 05:56 PM
                  0 responses
                  9 views
                  0 likes
                  Last Post jaybedreamin  
                  Started by DJ888, 04-16-2024, 06:09 PM
                  6 responses
                  19 views
                  0 likes
                  Last Post DJ888
                  by DJ888
                   
                  Started by Jon17, Today, 04:33 PM
                  0 responses
                  6 views
                  0 likes
                  Last Post Jon17
                  by Jon17
                   
                  Started by Javierw.ok, Today, 04:12 PM
                  0 responses
                  16 views
                  0 likes
                  Last Post Javierw.ok  
                  Working...
                  X