Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Trailing Stop, StopLoss, Profit Target Combo

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

    Trailing Stop, StopLoss, Profit Target Combo

    Hiya expert Ninja Programmers!

    Here is the goal:

    1 - Set stoploss for 2 car entry
    2 - Move stoploss to entry price when current price moves to 4 ticks past
    3 - Take profit target of 1 car at 4 ticks
    4 - Trail stop final car 4 ticks back

    Here is what I have cobbled together so far from multiple sources (SampleScaleOut, SamplePriceModification) (deleted the sections that seemed unimportant):


    // This namespace holds all strategies and is required. Do not change it.
    namespace NinjaTrader.Strategy
    {
    /// <summary>
    /// Short Trending check
    /// </summary>
    [Description("Short Trending check")]
    public class TrendShort : Strategy
    {
    #region Variables
    // Wizard generated variables
    private int slopeLow = -20; // Default setting for SlopeLow
    private int stochLow = 30; // Default setting for StochLow
    // 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()
    {
    SetStopLoss(CalculationMode.Ticks, 5);
    SetProfitTarget("Short 1a", CalculationMode.Ticks, 4);

    CalculateOnBarClose = false;
    }

    /// <summary>
    /// Called on each bar update event (incoming tick)
    /// </summary>
    protected override void OnBarUpdate()
    {
    // Condition for stop loss/nbe move - reset the stop loss when closed
    if (Position.MarketPosition == MarketPosition.Flat)
    {
    SetStopLoss(CalculationMode.Ticks, 5);
    }

    // If short, allow for stoploss mod to b/e
    else if (Position.MarketPosition == MarketPosition.Short)
    {
    // Once price is less than entry price - 4 ticks, set stop loss to b/e
    if (Close[0] < Position.AvgPrice + 4 * TickSize)
    {
    SetTrailStop(CalculationMode.Ticks, 5);
    }
    }
    (If Conditions)

    EnterShort("Short 1a");
    EnterShort("Short 1b");
    }
    }

    #region Properties
    [Description("")]
    [Category("Parameters")]
    public int SlopeLow
    {
    get { return slopeLow; }
    set { slopeLow = Math.Max(-70, value); }
    }

    [Description("")]
    [Category("Parameters")]
    public int StochLow
    {
    get { return stochLow; }
    set { stochLow = Math.Max(1, value); }
    }
    #endregion
    }
    }

    So as you can see, I am using the "split order" method in order to take profit on 1 car, whilst performing action on the other. You probably also notice my use of the TrailStop command in the midst of checking and resetting if/when price moves past the 4 tick target.

    The script compiles ok - but it does not reveal the results I would like - specifically its still taking both cars out at 4 ticks, instead of trailstopping the second.

    I hope one of you senior types will show mercy on me, and teach me what I am missing - probably something simple

    Thanks:

    Bannor
    Last edited by Bannor; 12-19-2008, 01:25 PM.

    #2
    You cannot call SetTrailStop() in the middle like that. Set() methods need to be called before the entry order occurs for them to take effect. You need to explicitly say SetTrailStop() for that order beforehand. Problem you will have is you cannot call SetStopLoss() and SetTrailStop() simultaneously for the same order.

    If you really want this trailing stop to kick in after being a regular stop you cannot use Set() methods. You will need to manually program it with ExitLongStop() and just modify the order as if it were a trailing stop. Review this thread if you want to do this http://www.ninjatrader-support2.com/...d.php?t=10344&
    Josh P.NinjaTrader Customer Service

    Comment


      #3
      Ok - I read that about a thousand times in other posts . . .

      I thought I would be successful, via using your posted split entry method for taking partial profits at target, combined with moving the stoploss up to breakeven at target.

      I will read the snippet and keep trying

      Comment


        #4
        Split entries allows you to separate out the orders for exiting. You still cannot attach a SetStopLoss() to one order and then replace it with SetTrailStop() at a later point in time. You can however attach SetStopLoss() to one and SetTrailStop() to the other.
        Josh P.NinjaTrader Customer Service

        Comment


          #5
          Well, I dont think that would work, because I need to treat all of the contracts the same at the beginning - ie stop loss until price moves to entry + ticks.

          So for example;

          2 cars short at 800. Stoploss set at 801.25 (5 tick stoploss).

          Currentprice moves to 799 - stoploss moves to 800 for both cars.

          Currentprice moves to 798.75 (1 tick past the profittargetprice for 1 car), 1 car bought at 4 ticks profit, 2nd car changes to trailing stop.

          Currentprice meanders down to 796, then bounces back up to 797 - trailing stop buys final car and closes trade for total of 4 points profit (16 ticks).

          This is actually a pretty common exit scenario for Futures traders, where we enter with multiple contracts, take some number of them off at price targets, and ultimately allow the final contract(s) to "run" with a trailing stop (or ATR or discretionary or whatever), so that we can get a bit of profit out of the move but also gain the additional benefit if the trade continues in our direction.

          So what I can do is place the entire "trailStop loop" inside the bracket labelled "Once price is less than entry price -4 ticks . . ."?

          Comment


            #6
            For what you want you cannot use Set() methods then. You will need to program your own as demonstrated by the link I provided earlier.
            Josh P.NinjaTrader Customer Service

            Comment


              #7
              Ok.

              I am obviously doing something incorrect here. Here is my code snippet - where I am trying to place a short order, trail stop it, move the stop to entry at a certain point, take a car off with profit, and trailstop the remaining car.

              protected override void OnBarUpdate()
              {
              // Condition set for price action - and EnterShort - and set SLPrice
              if (..Entry Conditions..)
              {
              // Enter default qty short
              EnterShort();
              Print(Time[0] + "Entered Short: " + Position.AvgPrice);
              // Set SLPrice to 1.25 up from entry
              SLPrice = Position.AvgPrice + 1.25;
              Print("Entry Price: " + Position.AvgPrice);
              Print("SLPrice: " + SLPrice);
              }

              // Check if Position open, if not then reset SLPrice to 0
              if (Position.MarketPosition == MarketPosition.Flat)
              {
              SLPrice = 0;
              }

              // If short, allow for stoploss mod to b/e
              else if (Position.MarketPosition == MarketPosition.Short)
              {
              // Once price is less than entry price - 5 ticks, set stop loss to order entry, and exit 1 car
              if (Close[0] < Position.AvgPrice - 5 * TickSize)
              {
              SLPrice = Position.AvgPrice;
              ExitShort(1);
              Print("NET BE SL Price plus 1 exit: " + SLPrice);
              }
              // Price less than (SLPrice-1 pt)? Modify SLPrice to equal Price plus 1
              if (Close[0] < SLPrice - 1)
              {
              SLPrice = Close[0] + 1;
              Print("Alter SLPrice: " + SLPrice);
              }
              // Check Price against SLStop - if equal to or greater than, exit all remaining cars
              if (Close[0] >= SLPrice)
              ExitShort();
              Print("Exit Second Contract");
              }
              }

              And here is my output window with trace set "on":

              10/15/2008 9:09:00 AM Entered internal PlaceOrder() method at 10/15/2008 9:09:00 AM: Action=SellShort OrderType=Market Quantity=2 LimitPrice=0 StopPrice=0 SignalName='' FromEntrySignal=''
              10/15/2008 9:09:00 AMEntered Short: 0
              Entry Price: 0
              SLPrice: 1.25
              10/15/2008 9:10:00 AM Entered internal PlaceOrder() method at 10/15/2008 9:10:00 AM: Action=BuyToCover OrderType=Market Quantity=0 LimitPrice=0 StopPrice=0 SignalName='' FromEntrySignal=''
              Exit Second Contract
              10/15/2008 12:07:00 PM Entered internal PlaceOrder() method at 10/15/2008 12:07:00 PM: Action=SellShort OrderType=Market Quantity=2 LimitPrice=0 StopPrice=0 SignalName='' FromEntrySignal=''
              10/15/2008 12:07:00 PMEntered Short: 0
              Entry Price: 0
              SLPrice: 1.25

              So, it seems I am not calculating SLPrice correctly? Something to do with Position.AvgPrice?

              Help!

              B

              Comment


                #8
                If I:

                Short()

                Shouldn't:

                Position.AvgPrice

                return the price I shorted?

                Comment


                  #9
                  Hi Bannor, please do us a favor and post the code next time with the code commands, which makes it much easier to read on the forum pages. First thing I would recommend you, is scale in to scale out and use unique order names to identify each signal and the debug from there...yes Position.AvgPrice should contain your entry price.

                  Comment


                    #10
                    #region Using declarations
                    using System;
                    using System.ComponentModel;
                    using System.Diagnostics;
                    using System.Drawing;
                    using System.Drawing.Drawing2D;
                    using System.Xml.Serialization;
                    using NinjaTrader.Cbi;
                    using NinjaTrader.Data;
                    using NinjaTrader.Indicator;
                    using NinjaTrader.Gui.Chart;
                    using NinjaTrader.Strategy;
                    #endregion

                    // This namespace holds all strategies and is required. Do not change it.
                    namespace NinjaTrader.Strategy
                    {
                    /// <summary>
                    /// Short Trending check
                    /// </summary>
                    [Description("Short Trending check")]
                    public class TrendShort : Strategy
                    {
                    #region Variables
                    // Wizard generated variables
                    private int slopeLow = -20; // Default setting for SlopeLow
                    private int stochLow = 30; // Default setting for StochLow
                    // User defined variables (add any user defined variables below)
                    private double SLPrice = 0;
                    #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()
                    {
                    CalculateOnBarClose = false;
                    TraceOrders = true;
                    }

                    /// <summary>
                    /// Called on each bar update event (incoming tick)
                    /// </summary>
                    ///
                    protected override void OnBarUpdate()
                    {
                    // Condition set for price action - and EnterShort - and set SLPrice
                    if (Close[0] > Open[0])
                    {
                    // Enter default qty short
                    EnterShort();
                    Print(Time[0] + "Entered Short: " + Position.AvgPrice);
                    // Set SLPrice to 5 ticks up from entry
                    SLPrice = Position.AvgPrice + 5 * TickSize;
                    Print("Entry Price: " + Position.AvgPrice);
                    Print("SLPrice: " + SLPrice);
                    }

                    // Check if Position open, if not then reset SLPrice to 0
                    if (Position.MarketPosition == MarketPosition.Flat)
                    {
                    SLPrice = 0;
                    }

                    // If short, allow for stoploss mod to b/e
                    else if (Position.MarketPosition == MarketPosition.Short)
                    {
                    // Once price is less than entry price - 5 ticks, set stop loss to order entry, and exit 1 car
                    if (Close[0] < Position.AvgPrice - 5 * TickSize)
                    {
                    SLPrice = Position.AvgPrice;
                    ExitShort(1);
                    Print("NET BE SL Price plus 1 exit: " + SLPrice);
                    }
                    // Price less than (SLPrice-1 pt)? Modify SLPrice to equal Price plus 1
                    if (Close[0] < SLPrice - 1)
                    {
                    SLPrice = Close[0] + 4 * TickSize;
                    Print("Alter SLPrice: " + SLPrice);
                    }
                    // Check Price against SLStop - if equal to or greater than, exit all remaining cars
                    if (Close[0] >= SLPrice)
                    ExitShort();
                    Print("Exit Second Contract");
                    }
                    }

                    #region Properties
                    [Description("")]
                    [Category("Parameters")]
                    public int SlopeLow
                    {
                    get { return slopeLow; }
                    set { slopeLow = Math.Max(-70, value); }
                    }

                    [Description("")]
                    [Category("Parameters")]
                    public int StochLow
                    {
                    get { return stochLow; }
                    set { stochLow = Math.Max(1, value); }
                    }

                    #endregion
                    }
                    }

                    Comment


                      #11
                      Let me explain again exactly what I am trying to accomplish, and why breaking the order into parts and taking those parts won't work.

                      Step 1: On Short Entry Signal, Short 2 cars, and set a Stop Loss to 5 ticks above the entry point for both cars.

                      Step 2: On Price moving 5 ticks below entry point, take 1 car off in profit at market price, and leave the remaining car on with a 5 tick trailing stop.

                      Thats it, pretty simple stuff, or should be.

                      If I were to split the cars, so for example 1 car has a stoploss and profittarget on it, and the other is merely a trailing stop, then the trailing stop car gets stopped early if the price "meanders".

                      In other words, if price moves just a few ticks down, then falls back below the entry point, the contract gets closed at the trailing stop price, versus holding the contract open for the entire "stop loss" distance of 5 ticks.

                      So, it makes more sense to me to open the trade with a short(2) and a stop loss of 5 ticks for both, check for conditions, if conditions get to "break even move time" then exitshort(1), and set a trailing stop for the remaining car.

                      Make sense?

                      B

                      Comment


                        #12
                        Hi Bannor, thanks for posting the code but I meant the code tags instead, this will make sure

                        Code:
                        your NinjaScript code is formatted well
                        Looking at your code you modify the variable that holds your custom stop loss value, but you do not call a stop order modified with this, such as ExitLongStop() - http://www.ninjatrader-support.com/H...ShortStop.html

                        Please also check out this reference sample here - http://www.ninjatrader-support2.com/...ead.php?t=3222

                        Comment


                          #13
                          The set commands you have referenced will not work in this scenario, as Josh has pointed out.

                          What I have to do is set up test conditions and if/then loops for the current price action, and then move exit levels and take profit levels when certain levels are met.

                          I am hoping someone that knows how to do that can give me some ideas on looping.

                          B

                          Comment


                            #14
                            Bannor,

                            Unfortunately we cannot code every aspect out for you. The general idea you already have. Just call ExitLongStop() over again whenever you want to make a change to the order. You create the if-else logic and just have it call ExitLongStop().
                            Josh P.NinjaTrader Customer Service

                            Comment


                              #15
                              Josh:

                              Ok I am getting closer - and now I have a new issue buried inside this beast.

                              I stumbled over the following:

                              When indicators or strategies are running on historical data, OnBarUpdate() is only called on the close of each historical bar even if this property is set to false. This is due to the fact that with a historical data set, only the OHLCVT of the bar is known and not each tick that made up the bar.

                              I am building a strategy for the ES, so historical intrabar "tick by tick" calculations are critical to evaluating the proper entry/exit strategies.

                              To be simple, I need to calculate my entries and exits on a tick by tick basis, not on what the close of the overall bar is. I understand this is how the strategy will run in real time, but I need to be able to evaluate history in the same manner.

                              I noticed this as I dig deeper into debugging my loops, and I am finding radically different Close[0] prices from loop to loop, indicating lots of price action intra-bar.

                              Any ideas how to circumvent this issue? Can I run the strategy against a faster timeframe?

                              Thanks:

                              B

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                              0 responses
                              648 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
                              109 views
                              0 likes
                              Last Post Mindset
                              by Mindset
                               
                              Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                              0 responses
                              573 views
                              1 like
                              Last Post Geovanny Suaza  
                              Started by RFrosty, 01-28-2026, 06:49 PM
                              0 responses
                              575 views
                              1 like
                              Last Post RFrosty
                              by RFrosty
                               
                              Working...
                              X