Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Move Stop Loss

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

    Move Stop Loss

    Hi all, im trying to create a strategy that will work the same in Back-testing and Real-time, however im struggling with the Stop Loss Order.

    Don't want to use Trailing Stops, i wanna give price some space, but if i increment the Trailing Stop i also increase its the initial position unnecessarily increasing my risk, i just want a Stop Order that:

    When position is entered stays: -20 ticks behind
    if price has gone positive 60 ticks then SL = Brake even
    if price has gone positive 100 ticks then SL = 60 ticks positive

    i know i cant use both a Stop Loss order and a Trailing Stop at the same time,
    so i figure i have to create conditions to move the SL if those conditions are met.

    dunno how to do that, my programming skills are limited, a little help please!

    Thank you in advance!

    #2
    Hello kabott,

    Thanks for your post.

    Correct, you cannot use both the settrail and setstop at the same time. Here I think you will want to use the SetStopLoss() method and manage its position as you have outlined.

    In the initialize section set up the SetStopLoss() at 20 ticks so that you have an initial stop position for the first order.

    For managing the stop you could do something like:

    Code:
    if (Close[0] > Position.AvgPrice + 100 *TickSize && !SecondLevel)  // test for > 100 tick profit
    {
    SetStopLoss ("", CalculationMode.Price, Position.AvgPrice+ 60 *TickSize, false);  // set for +60 profit
    SecondLevel = true;  // set flag so only do this once
    }
    
    if (Close[0] > Position.AvgPrice + 60 * TickSize && !FirstLevel)
    {
    SetStopLoss ("", CalculationMode.Price, Position.AvgPrice+ 1 *TickSize, false);  // Breakeven + 1 tick
    FirstLevel = true; // Set flag so we only do this once
    }
    Note that you would have to create and initialize to false the bools FirstLevel and SecondLevel.

    I would also add this in your code to reset things

    Code:
    if (Position.MarketPosition ==MarketPosition.Flat && doItOnce)
    {
    SetStopLoss ("", CalculationMode.Ticks, 20, false);  // reset to -20
    FirstLevel = false;
    SecondLevel = false;
    doItOnce = false;   // note set this to TRUE when you have placed an order
    }
    Of course always test things in simulation.
    Paul H.NinjaTrader Customer Service

    Comment


      #3
      Thanks Paul, im a bit lost, where should i use that code? something like this?


      protected override void Initialize()

      SetStopLoss ("StopOrder", CalculationMode.Price, Position.AvgPrice -( 100 *TickSize ), false); // Default Stop


      protected override void OnBarUpdate()


      if (Close[0] > Position.AvgPrice + 100 *TickSize && !SecondLevel) // test for > 100 tick profit
      {
      SetStopLoss ("", CalculationMode.Price, Position.AvgPrice+ 60 *TickSize, false); // set for +60 profit
      SecondLevel = true; // set flag so only do this once
      }

      if (Close[0] > Position.AvgPrice + 60 * TickSize && !FirstLevel)
      {
      SetStopLoss ("", CalculationMode.Price, Position.AvgPrice+ 1 *TickSize, false); // Breakeven + 1 tick
      FirstLevel = true; // Set flag so we only do this once
      }


      ive seen so many examples that i have a mishmash in my mind and get lost in confusion, can you show me how should the proper structure go?

      Thanks again!

      Comment


        #4
        Ok, i made a mess :P couple errors appeared:

        "doltdoes not exist in the current context"
        "Exit on close does not exists in the current.."

        i guess i understand how the script should work, but i dont know the language well enough.

        here is the strategy

        StrategyTest2.cs

        Comment


          #5
          Hello kabott,

          Thanks for your reply.

          Here is what you need in the Initialize section:

          SetStopLoss ("", CalculationMode.Ticks, 20, false) ; // initial 20 tick stop

          All the other code would need to be in the OnBarUpdate()

          You will need to declare the bools, doItOnce, FirstLevel and SecondLevel as previously discussed, in the same section as where you other variables are declared.

          In the onBarUpdate section, logically I would have:

          1) Order entry code
          2) trailing stop code
          3) reset code

          Nothing magic here just a flow of thoughts.

          For debugging, make sure you have the variable names correct and capitalization does count.
          Paul H.NinjaTrader Customer Service

          Comment


            #6
            K, now it compiles but no entry is being placed, in the Log says:

            "Failed to call method Initialize for strategy... Position property cant be accessed from initialize method"
            Attached Files
            Last edited by kabott; 09-01-2015, 08:37 AM.

            Comment


              #7
              Hello kabott,

              Thanks for your reply.

              In the initialize section you have:
              SetStopLoss ("StopOrder", CalculationMode.Price, Position.AvgPrice -( initialStopLoss *TickSize ), false); // Default Stop

              You cannot use Position.AvgPrice here because you have not taken a position when you start the strategy. Initialize is called before orders are placed.

              Here is what you need in the Initialize section:

              SetStopLoss ("", CalculationMode.Ticks, 20, false) ; // initial 20 tick stop
              Paul H.NinjaTrader Customer Service

              Comment


                #8
                Hey Paul, i did it, i got it running properly, need to test it real time for some time now, i was wondering, perhaps isn't necessary but well..is there a way to optimize this code so its more efficient?

                if (Position.MarketPosition == MarketPosition.Long)
                {
                if ( ( High[0] < Position.AvgPrice + ( ifcurrentPriceAt2 * TickSize) ) && High[0] > Position.AvgPrice + ( ifcurrentPriceAt1 * TickSize) )

                SetStopLoss ("target1", CalculationMode.Price, Position.AvgPrice + ( moveStopTo1 * TickSize ) , false);


                else if ( High[0] > Position.AvgPrice + ( ifcurrentPriceAt2 * TickSize) )

                SetStopLoss ("target1", CalculationMode.Price, Position.AvgPrice + ( moveStopTo2 * TickSize ) , false); // Default Stop

                }


                thank you!

                Comment


                  #9
                  Hello kabott,

                  Thanks for your reply.

                  Congrats on the progress of your code.

                  Your code looks like it could move the stop back and forth depending on the current price and this may be okay if that is what you want to do. However if you only want to move the stop once (to each level), then you might consider adding some bool condition variables to set and check (and reset when flat).

                  If you look at the code I originally provided what I did was to use a couple of bools so that code segments are only executed once when their conditions are reached.
                  Paul H.NinjaTrader Customer Service

                  Comment


                    #10
                    mmhh..how you mean "back and forth"? like retrace back the stop?

                    no i dont want that, only move up (in this case for Long entries)




                    private void GoLong()
                    {
                    SetStopLoss ("target1", CalculationMode.Price, Close[0] - ( initialStopLoss * TickSize ) , false); // Default Stop
                    EnterLong ( "target1" );
                    SetProfitTarget ("target1" , CalculationMode.Price, Close[0] + ( takeProfitTarget * TickSize));

                    }

                    So, this is: If price < than level 2 but price > level 1, go to brake even (move it to stop 1)

                    if ( ( High[0] < Position.AvgPrice + ( ifcurrentPriceAt2 * TickSize) ) && High[0] > Position.AvgPrice + ( ifcurrentPriceAt1 * TickSize) )

                    SetStopLoss ("target1", CalculationMode.Price, Position.AvgPrice + ( moveStopTo1 * TickSize ) , false);



                    else if price is higher than target 2 move it to level 2

                    else if ( High[0] > Position.AvgPrice + ( ifcurrentPriceAt2 * TickSize) )

                    SetStopLoss ("target1", CalculationMode.Price, Position.AvgPrice + ( moveStopTo2 * TickSize ) , false); // Default Stop

                    }

                    Comment


                      #11
                      Hello kabott,

                      Thanks for your reply.

                      As I am unsure of the values you are using, the question to ask: is it possible that if price reaches your last level that price could fall down to the second condition and actually reset the the stop loss to breakeven before hitting the 2nd level stoploss? You don't need to answer here, just a question to ask your self and above all else test out.

                      Alternatively you can ensure that won't happen by using a bool that says you have already set the first level. You can also use a bool that says you have set the last level and this way make your code more efficient because once the levels are set no need to check further, right? If you look at my original code that was how I use the bool variables, to protect against resetting the stop and to stop looking once it was set.
                      Paul H.NinjaTrader Customer Service

                      Comment


                        #12
                        hmm.. ok, ill be trying that now

                        this compiles, but i don't see the stop changing position in back test, i only see default stop and take profit. the thing is im using 2 diferent examples i found, on is yours and the other one comes from a video tutorial from BigMike's .. and trying to make this work basically by brute force lol



                        private int brakeEvenTarget = 60; // If price is here
                        private int brakeEvenLevel = 1; // then stop goes BE +1

                        private int trailStopTarget = 80; // if price is here
                        private int trailStopLevel = 40; // then stop goes here


                        protected override void Initialize()

                        private void GoLong()
                        {
                        SetStopLoss ("target1", CalculationMode.Price, Close[0] - ( initialStopLoss * TickSize ) , false); // Default Stop
                        EnterLong ( "target1" );
                        SetProfitTarget ("target1" , CalculationMode.Price, Close[0] + ( takeProfitTarget * TickSize));

                        }


                        protected override void OnBarUpdate()

                        if (Position.MarketPosition != MarketPosition.Flat) return;
                        {

                        // Rising
                        if ( ( Close[0] > _superTrend.SPFlipper[0] )
                        && ( Close[0] < _superTrend.SPCenterAverage[0] || Close[1] < _superTrend.SPCenterAverage[1] )
                        && ( Close[2] < Open[2] && Close[1] < Open[1] && Close[0] > Open[0] && FirstTickOfBar ) )



                        GoLong();

                        }



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

                        if ( High[0] > Position.AvgPrice + ( TrailStopTarget * TickSize) && !SecondLevel )
                        {

                        SetStopLoss ("target1", CalculationMode.Price, Position.AvgPrice + ( TrailStopLevel * TickSize ) , false); // Default Stop
                        SecondLevel = true;

                        }
                        else if ( ( High[0] < Position.AvgPrice + ( TrailStopTarget * TickSize) ) && High[0] > Position.AvgPrice + ( BrakeEvenTarget * TickSize) && !FirstLevel )
                        {

                        SetStopLoss ("target1", CalculationMode.Price, Position.AvgPrice + ( BrakeEvenLevel * TickSize ) , false);
                        FirstLevel = true; // Set flag so we only do this once

                        }

                        }




                        if (Position.MarketPosition ==MarketPosition.Flat && doItOnce)
                        {
                        SetStopLoss ("", CalculationMode.Ticks, 20, false); // reset to -20
                        FirstLevel = false;
                        SecondLevel = false;
                        doItOnce = false; // note set this to TRUE when you have placed an order
                        }
                        Last edited by kabott; 09-01-2015, 09:34 AM.

                        Comment


                          #13
                          Well.. no luck, the stop is still fixed at the default level (120) ..dunno what else to try i cant make the booleans you suggested work


                          this are the seetings im using

                          private int takeProfitTarget = 320; // default
                          private int initialStopLoss = 120; //default

                          private int brakeEvenTarget = 60; // If price is here
                          private int brakeEvenLevel = 1; // then stop goes BE +1

                          private int trailStopTarget = 180; // if price is here
                          private int trailStopLevel = 60; // then stop goes here

                          Click image for larger version

Name:	2015-09-01_130736.jpg
Views:	1
Size:	45.2 KB
ID:	874475
                          see here price went up above 200 pips and stop remained at default (-120 pips)


                          StrategyTest2.cs

                          Comment


                            #14
                            Hello kabott,

                            Thanks for your reply.

                            I will take a deeper look at your code and reply later. on initial view I suspect the bool doItOnce is not being set true when you place an order.
                            Paul H.NinjaTrader Customer Service

                            Comment


                              #15
                              Hello kabott,

                              I've reviewed and adjusted your code, please review and test.

                              The changes were to initialize doItOnce to True, and also set doItOnce true after each order is placed.

                              I changed the initial stop from using close price - initialstoploss *TickSize to using calculationmode of ticks and just initialstop loss. Where you are setting it, close is okay but using tick mode sets it exactly according to the entry price when the entry price is determined.

                              I eliminated the SetStopLoss reset I had added because you are already resetting it in the go long/short section.
                              Attached Files
                              Paul H.NinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by gnocchi, Today, 11:56 AM
                              1 response
                              2 views
                              0 likes
                              Last Post NinjaTrader_Zachary  
                              Started by FAQtrader, Today, 12:00 PM
                              0 responses
                              3 views
                              0 likes
                              Last Post FAQtrader  
                              Started by geddyisodin, Today, 05:20 AM
                              5 responses
                              32 views
                              0 likes
                              Last Post NinjaTrader_Gaby  
                              Started by bmartz, Today, 09:30 AM
                              2 responses
                              13 views
                              0 likes
                              Last Post bltdavid  
                              Started by f.saeidi, Today, 11:02 AM
                              1 response
                              5 views
                              0 likes
                              Last Post NinjaTrader_BrandonH  
                              Working...
                              X