Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Advanced StopLoss with OnMarketData

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

    Advanced StopLoss with OnMarketData

    Code attached.

    I'm trying to develop a StopLoss that is initiated on every Buy/Sell. At which point, after the CurrentAsk > AvgPosition + 5, set a trailing stop loss that moves within 15 points. Now, I have this working, but it just seems as though the stop loss trails but never "plants" so to speak. Take a look at my code and see what you think. It's kind of hard to explain. I want to use COBC = True for my indicator reasons, but use the OnMarketData mode for tick-by-tick analysis of the price and adjust the stop loss based on that. In My OnBarUpdate section, I have the type of stoploss I want, spelled out. Let me know if there's a better way to code this, or if the data there needs to be over in OnMarketData. Thanks for your help, time, and patience.
    Attached Files

    #2
    Hello rdavido,

    I think I am understanding what you mean by plant.

    You are saying that the stop loss is moving in both directions instead of only moving toward the current price. In other words, it stays the exact distance from current price even if the price comes back toward the stop loss.

    Is this correct?

    This is because of your condition that moves the stop.

    // If a long position is open, allow for stop loss modification to breakeven
    if (Position.MarketPosition == MarketPosition.Long)
    {
    // Once the price is greater than entry price, plus 5 ticks, readjust Stop
    if (GetCurrentAsk() > (Position.AvgPrice + 2 * TickSize))
    {
    SetStopLoss(CalculationMode.Price, High[HighestBar(High, 3)] - 20 * TickSize);
    }
    }

    If the Position is long and the current ask is greater than the entry plus 2 ticks then move the stop to high minus 20 ticks. This is true on every bar after two ticks of profit, even if the price has moved back toward you.

    In your condition, you need to track the price that the stop loss is currently at. Then check to see if the current highest bar is greater than the saved stop price plus 20 ticks. if it is, move the stop to the to the highest bar minus 20 ticks.

    I have an example I have made that demonstrates how to track the stop loss price to ensure that the stop only moves in one direction which I am attaching to this post.
    Attached Files
    Last edited by NinjaTrader_ChelseaB; 04-02-2015, 10:11 AM.
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Ok, this is working better, however, the stop is not readjusting to intrabar new highs, only at the start of a new bar. I have COBC = true, however, the trailing part is within OnMarketData and should be tick by tick. Any thoughts?

      Code:
      protected override void OnMarketData(MarketDataEventArgs e)
                  {                        
                      if (e.MarketDataType == MarketDataType.Ask && trail == true && Position.MarketPosition == MarketPosition.Long)
                      {
                          if (e.MarketData.Ask.Price > Position.AvgPrice + 5 * TickSize)
                          {
                          currentStop = High[HighestBar(High, 3)] - 15 * TickSize;
                          SetStopLoss(CalculationMode.Price, currentStop);
                          }
                          
                          if (e.MarketData.Ask.Price < Position.AvgPrice - 5 * TickSize)
                          {
                          currentStop = 10;
                          SetStopLoss(CalculationMode.Ticks, currentStop);
                          }
                      }    
                      
                      if (e.MarketDataType == MarketDataType.Bid && trail == true && Position.MarketPosition == MarketPosition.Short)
                      {
                          // if Current Bid is less than where you bught, less 5 ticks
                          if (e.MarketData.Bid.Price < Position.AvgPrice - 5 * TickSize)
                          {
                          currentStop = Low[LowestBar(Low, 3)] + 15 * TickSize;
                          SetStopLoss(CalculationMode.Price, currentStop);
                          }
                          
                          if (e.MarketData.Bid.Price > Position.AvgPrice + 5 * TickSize)
                          {
                          currentStop = 10;
                          SetStopLoss(CalculationMode.Ticks, currentStop);
                          }
                      }

      Comment


        #4
        Hi rdavido,

        The code in the OnMarketData will trigger on a tick by tick basis.

        Below is a video that demonstrates that this works.
        http://screencast.com/t/tJEL3qxVabOa

        Your logic in OnMarketData is running at the same time as the logic in OnBarUpdate(). This can be confusing because both areas of code are moving the stop loss.

        Really you want one of them to move the stop, until the trail starts. Having a trail and breakeven movement conflict with each other does not make much sense.

        In the example that I provided for you, this allows the breakeven movements to happen first. After they are all completed, then the trail begins, but not until then.


        Further your logic for trailing in OnMarketData() for short trades is incorrect and will not work.

        Last, the logic in OnMarketData() for long trades, will allow the stop loss to move even if the price is falling. This is because you only require the current price to be 5 ticks above the stop, and you place the stop 10 ticks below. This means that the price would have to gap 5 ticks down for that condition to not be true and not move the stop loss.

        If you want to prevent the stop loss from moving, you need to use the same amount of ticks in the condition that you are placing the stop.
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          Ok, I have it working ALMOST like I want it, but only the LONG trailing stop works and the short side does not work. Could you look and see if there's any explanation? Thanks for all your kind help.

          Code:
                  protected override void OnBarUpdate()
                    {
                      if (ToTime(Time[0]) > ToTime(5, 30, 0) && ToTime(Time[0]) < ToTime(15, 59, 59))
                      {    
                      // Resets the stop loss to the original value when all positions are closed
                      if (Position.MarketPosition == MarketPosition.Flat)
                      {
                          currentStop = 0;
                          trail = false;
                          SetStopLoss(CalculationMode.Ticks, stoplossticks);
                      }
                      
                      {
                                  
                          // Condition set 1
                          if ((BarsSinceExit() > 3 || BarsSinceExit() == -1) && CrossAbove(Stochastics(3, 14, 3).K, Stochastics(3, 14, 3).D, 1))
                          if (Position.MarketPosition == MarketPosition.Flat)
                          {
                              EnterLong("LONG");
                              currentStop = 15;
                              SetStopLoss(CalculationMode.Ticks, currentStop);
                              trail = true;                
                          }
                          
                          // Condition set 2
                          if ((BarsSinceExit() > 3 || BarsSinceExit() == -1) && CrossAbove(Stochastics(3, 14, 3).D, Stochastics(3, 14, 3).K, 1))
                          if (Position.MarketPosition == MarketPosition.Flat)
                          {
                              EnterShort("SHORT");
                              currentStop = 15;
                              SetStopLoss(CalculationMode.Ticks, currentStop);
                              trail = true;
                          }
                      }
                      }
                  }
                  protected override void OnMarketData(MarketDataEventArgs e)
                      {
                      if (Position.MarketPosition == MarketPosition.Long)
                      if (e.MarketDataType == MarketDataType.Last && trail == true && e.Price > currentStop + 12 * TickSize)
                      {
                          currentStop = High[HighestBar(High, 3)] - 15 * TickSize;
                          SetStopLoss(CalculationMode.Price, currentStop);
                      }
                      if (Position.MarketPosition == MarketPosition.Short)    
                      if (e.MarketDataType == MarketDataType.Last && trail == true && e.Price < currentStop - 12 * TickSize)
                          {
                          currentStop = Low[LowestBar(Low, 3)] + 15 * TickSize;
                          SetStopLoss(CalculationMode.Price, currentStop);
                          }
                      }

          Comment


            #6
            Hi rdavido,

            I'm not seeing anything jump out at me.

            I would add prints to your code and make sure all the values are what you expect.

            Is the entry order placing at the correct time?

            Is the breakeven code or the OnMarketData code causing the issue?
            (try commenting one out and looking for the behavior)

            Are the price values correct?

            Print(e.Price+" < "+(currentStop - 12 * TickSize));
            Print(Low[LowestBar(Low, 3)] + 15 * TickSize);
            Chelsea B.NinjaTrader Customer Service

            Comment


              #7
              So, when I added prints, nothing outputs on the SHORT side, but they do on the LONG side. It doesn't make any sense. It's almost like it's ignoring anything short and only handling long orders. It also doesn't reset my currentStops to anything. For example, when market position = flat, set reset stop, however, it's not doing it in the script. It's not following. I have attached my latest.
              Attached Files

              Comment


                #8
                Hello rdavido,

                If the prints for the short side are not appearing, add a print that prints the values of the variables used in the condition that triggers that code outside of that condition (so the print appears even if the condition is false).

                For example:
                Print(e.MarketDataType.ToString()+" == Last && "+trail.ToString()+" == true && "+e.Price.ToString()+" > "+(currentStop + 15 * TickSize));

                if (e.MarketDataType == MarketDataType.Last && trail == true && e.Price > currentStop + 15 * TickSize)

                What prints out when you add this print?
                Chelsea B.NinjaTrader Customer Service

                Comment


                  #9
                  Code:
                  Last == Last && True == true && 48.93 > 48.83
                  0
                  Last == Last && True == true && 48.94 > 48.84
                  0
                  Last == Last && True == true && 48.94 > 48.84
                  0
                  Last == Last && True == true && 48.94 > 48.84
                  0
                  Last == Last && True == true && 48.94 > 48.84
                  0
                  Last == Last && True == true && 48.94 > 48.84
                  0
                  Last == Last && True == true && 48.94 > 48.84
                  0
                  Last == Last && True == true && 48.93 > 48.83
                  0
                  Last == Last && True == true && 48.93 > 48.83
                  0
                  Last == Last && True == true && 48.93 > 48.83
                  0
                  Last == Last && True == true && 48.93 > 48.83
                  0
                  Last == Last && True == true && 48.93 > 48.83
                  0
                  Last == Last && True == true && 48.94 > 48.84
                  0
                  Last == Last && True == true && 48.93 > 48.83
                  0
                  Last == Last && True == true && 48.93 > 48.83
                  0
                  Last == Last && True == true && 48.94 > 48.84
                  0
                  Last == Last && True == true && 48.94 > 48.84
                  0
                  Very strange. My stop loss does not trail, although the Print settings look correct. Now, the "0" corresponds to currentStop which differs from the line before print e.Price > currentStop + 5 * TickSize

                  Comment


                    #10
                    Please backtest this in MARKET REPLAY and let me know if you get different results. I even made new variables to try to parse out any issues with currentStop, but still no success.
                    Attached Files

                    Comment


                      #11
                      Hello rdavido,

                      It looks like you missed part of my suggestion.

                      add a print that prints the values of the variables used in the condition that triggers that code outside of that condition (so the print appears even if the condition is false).
                      You have more than one print. How are you identifying this print? How do you know that its coming from the print in the short side? (Maybe this is coming from the print on the long side)

                      Are you having trouble with the long side too? Why are there prints for the long side? What information are you trying to find?


                      When I ran this, I looked for prints coming out when the strategy was in a short position. I am not seeing any prints.
                      Chelsea B.NinjaTrader Customer Service

                      Comment


                        #12
                        Originally posted by NinjaTrader_ChelseaB View Post
                        Hello rdavido,

                        It looks like you missed part of my suggestion.



                        You have more than one print. How are you identifying this print? How do you know that its coming from the print in the short side? (Maybe this is coming from the print on the long side)

                        Are you having trouble with the long side too? Why are there prints for the long side? What information are you trying to find?


                        When I ran this, I looked for prints coming out when the strategy was in a short position. I am not seeing any prints.
                        I'm running prints for both the short side and long side to be able to tell if there's anything I'm doing wrong in coding the short side. All in all, it appears the long side is working, sometimes, but the short side is not. I can tell by whether or not e.Price is GREATER (long) or LESS THAN (short) currentStop. However, no matter what conditions I set, per your recent video, I cannot get the short side to work. Can you test on your end and see if there are conditions to make it work?

                        The only way I'm able to get this whole stop loss to work is if I instead parse it to

                        if(e.Price > Position.AvgPrice + 5 * TickValue) { condition }, but when I have it look at the currentStop, it does not work the way it is intended

                        Comment


                          #13
                          Hello rdavido,

                          I am not finding that the conditions will allow for the short side to work.

                          I am suggesting that there are no prints coming from the condition. I am suggesting that you add the print I have suggested outside of the condition so that you can see the print even if the condition does not evaluate as true. This will tell you why the condition is not evaluating as true.

                          I am also suggesting that you are getting confused about what is printing. Because you have multiple prints, I don't think you are identifying the prints correctly. I am fairly certain that the code for the short side is impossible to allow for that print to appear.
                          Chelsea B.NinjaTrader Customer Service

                          Comment


                            #14
                            How would one replace the initial hard setstoploss of x ticks with an indicator such as the parbolic sar?

                            Also, can you provide the short side of the custom trailing stop script?

                            Thanks..
                            Last edited by brucelevy; 02-03-2016, 02:59 PM.

                            Comment


                              #15
                              Hi brucelevy,

                              The SetStopLoss / SetProfitTarget can use a double when used with CalculationMode.Price. The ParabolicSAR() returns a double.

                              For example
                              SetStopLoss(CalculationMode.Price, ParabolicSAR(.02, 2, .02)[0]);

                              SetStopLoss - http://ninjatrader.com/support/helpG...etstoploss.htm

                              ParabolicSAR - http://ninjatrader.com/support/helpG...abolic_sar.htm

                              Attached is the same script adjusted to work with shorts.
                              Attached Files
                              Chelsea B.NinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                              0 responses
                              647 views
                              0 likes
                              Last Post Geovanny Suaza  
                              Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                              0 responses
                              369 views
                              1 like
                              Last Post Geovanny Suaza  
                              Started by Mindset, 02-09-2026, 11:44 AM
                              0 responses
                              108 views
                              0 likes
                              Last Post Mindset
                              by Mindset
                               
                              Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                              0 responses
                              572 views
                              1 like
                              Last Post Geovanny Suaza  
                              Started by RFrosty, 01-28-2026, 06:49 PM
                              0 responses
                              573 views
                              1 like
                              Last Post RFrosty
                              by RFrosty
                               
                              Working...
                              X