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

How to program StopLoss and Profit Trailing

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

    How to program StopLoss and Profit Trailing

    Hi,
    I'm working in a strategy and I add a StopLoss.
    But now I want to add ir a ProfitTrailing.
    I was thinking in use SetTrailStop but I have reades that this instruction doesno't work with SetStopLoss.
    How can I program a StopLoss, and Then when a X price with Y earnings are achieved set a Trailing Profit?

    #2
    Hello ervin,

    Thank you for your note.

    Is this a strategy you're coding manually, or are you using the Strategy Builder?

    A basic trail stop may be added in the Strategy Builder on the Stops and Targets screen. It should be noted that this is a very basic trailing stop and will trail by the same number of ticks each time - you cannot reduce the width of the trail stop after it's created.

    The Set methods in the Stops and Targets section of the Strategy Builder only allow for simple stops and targets that cannot be changed dynamically. You're correct that you cannot use both SetTrailStop() and SetStopLoss() for the same position. Programming by hand will offer more flexibility, but you can also create your own logic in Conditions and Actions that controls how you would like to exit.

    We can not offer services to design strategy logic in the support department, but you may conceptualize the following as an example of using Exit orders to mimic Trail stop functionality:
    1. If the strategy is flat, set a bool to controlling your auto trail behaviors to false. Then Enter.
    2. If the strategy is not flat and some condition happens that you would like to trigger your auto trail, set the bool to true.
    3. If the strategy is not flat and the bool is false, place your initial stop loss as an Exit Order.
    4. If the strategy is not flat and the bool is true, modify the Exit Order in association to the current market price.
    More information on using the Strategy Builder can be found below.

    Strategy Builder 301 - https://www.youtube.com/watch?v=HCyt90GAs9k

    If you are manually coding, you can simply call SetStopLoss again to update the price of the stop and create a trailing action.

    Here's an example from our help guide that shows modifying the stop loss to break even. This could be modified to continue updating the stop loss instead to create a trailing action after X amount of profit has been reached:



    Please let us know if we may be of further assistance to you.
    Kate W.NinjaTrader Customer Service

    Comment


      #3
      Hi,
      Thank you for your answer.
      I'm developing the strategy manually.
      In EURUSD, by example, how can I set trail profitt when the earnings achieve 200 USD, with a quantity of 100.000 en the enter order?

      Comment


        #4
        Also,
        Can I change the Order StopLoss CalculationMode from Currency to Price ?

        Comment


          #5
          And, In EURUSD how can I convert 500 USD to put StopLoose in PriceMode based in the Open Price fron the ORder?

          Comment


            #6
            Hello Ervin,

            Thank you for your note.

            To set your entry order to 100,000 units of currency, you'd need to specify that amount in your entry method. So, for example, you could do something like this for an entry order:

            EnterLong(100000);

            This would enter long for 100000 units (a standard lot). The Stop Loss will automatically be submitted for the same number of units.

            For forex, the pip size * difference in pips = currency PnL, so following that logic, the desired currency PnL in pips would just be Desired amount of loss / pip size = difference in pips. Since for EURUSD the US Dollar is the quote currency, you wouldn't need to do additional steps to convert to USD, so you could use CalculationMode.Pips instead once you've calculated the desired loss amount in pips.

            To update the stop loss once the order reaches at least $200 in profit, you can use something like:

            Code:
            if(Position.GetUnrealizedProfitLoss(PerformanceUnit.Currency, Close[0]) > 200)
            {
                 //modify your stop loss here
            }
            Please let us know if we may be of further assistance to you.
            Kate W.NinjaTrader Customer Service

            Comment


              #7
              Thak you again.
              Where do I get Pip Size?
              and If I want to use another pair by example AUDCAD, what changes must I have to do?

              Comment


                #8
                Hello ervin,

                Thank you for your reply.

                The TickSize variable can be used in a forex script to get the Pip Size for the instrument - it would give you the value for 10th pips however, so in most cases TickSize * 10 = Pip size.



                If you wish to use an instrument for which USD is not the quote currency and your account is funded in USD, such as AUDCAD, things get considerably more complex. Let me come up with an example script and I'll get that to you as soon as possible.

                Thanks in advance; I look forward to assisting you further.
                Kate W.NinjaTrader Customer Service

                Comment


                  #9
                  Hello erwin,

                  Thank you for your patience.

                  I've created a simple example strategy that will only work for CAD quoted currency pairs to place a stop $500 (or whatever amount) in USD from the entry price. So this could be used, for example, on AUDCAD using the Sim101 account for testing purposes.

                  If you want to use a pair with a different quoted currency, you'd need to modify the code to use the correct pair for the quoted currency with USD.

                  Since USDCAD is the pair we are using for our conversions, we have to divide 1 by the currently quoted price to get the USD value of 1 Canadian dollar to use in our calculations. If we were using a USD quoted pair for this calculation, we could simply use the quoted price instead.

                  Please let us know if we may be of further assistance to you

                  Attached Files
                  Kate W.NinjaTrader Customer Service

                  Comment


                    #10
                    Profit trailing is one of the most useful tools I have ever met in a program! Thank you a million for inventing it I use these functions really often as my trading strategies which I got here https://primexbt.com/blog/bitcoin-trading-strategies/ are based on them.
                    Last edited by Gabriel Jon; 11-05-2020, 06:28 PM.

                    Comment


                      #11
                      Kate-

                      I am trying to create my own version of a trail stop similar to the idea from post #1 in this thread.

                      I have stops that are in place prior to a position going 50 ticks in my favor.

                      When I get to 50 ticks, I want to have a trailing stop put in place from this point onward.

                      Please see the code I have so far

                      Code:
                       if (Position.MarketPosition == MarketPosition.Short
                      && (GetCurrentBid(0) + (50 * TickSize)) <= Position.AveragePrice
                      && (Position.Quantity ==1))
                      
                      {
                      FifteenTrailingStop = ExitShortStopMarket(0, true, Convert.ToInt32(Position.Quantity), (Low[0] + (25 * TickSize)), @"15TrailingStop", @"15Short2U-2D");
                      CancelOrder(FifteenLowExit);
                      FifteenTrailReached = true;
                      }
                      This is in the OnBarUpdate area of the code.

                      The issue I am having is that once a new bar is formed and that one has a new low, which could be higher than the previous low, I have a situation where my "trailing stop" could be moving backwards.

                      Do you have an idea as to how to prevent this backwards stop movement from happening?

                      Hopefully the question makes sense.

                      Thank you,

                      Nick

                      Comment


                        #12
                        Hello njmeyer713,

                        Thank you for your reply.

                        You could check whether FifteenTrailReached is true yet, assign the low + 25 ticks to a variable. Then, when the order is triggered again, before that, check that the current low is not higher than the low of the prior bar, and if it isn't, update the trailing stop.

                        So, something like this:

                        Code:
                        // instantiate variable at class level
                        private double TrailPrice;
                        
                        
                        // in OnBarUpdate:
                        
                        if (Position.MarketPosition == MarketPosition.Short
                        && (GetCurrentBid(0) + (50 * TickSize)) <= Position.AveragePrice
                        && (Position.Quantity ==1))
                        
                        {
                        if (FifteenTrailReached == false)
                        {
                        TrailPrice = Low[0] + (25 * TickSize);
                        }
                        else
                        {
                        // only move the trail if the current low is lower than prior low
                        if (Low[0] < Low[1])
                        {
                        TrailPrice = Low[0] + (25 * TickSize);
                        }
                        }
                        FifteenTrailingStop = ExitShortStopMarket(0, true, Convert.ToInt32(Position.Quantity), TrailPrice, @"15TrailingStop", @"15Short2U-2D");
                        CancelOrder(FifteenLowExit);
                        FifteenTrailReached = true;
                        }
                        Please let us know if we may be of further assistance to you.
                        Kate W.NinjaTrader Customer Service

                        Comment


                          #13
                          Kate,

                          Thank you for the response. I have followed your lead but I get an Error code when I reach the 50 ticks because the strat is trying to place a stopmar****rder at a price of 0.

                          I think this is coming from now setting the double variable equal to something when declaring it.

                          I at first glance I thought the code would have assigned TrailPrice a value before the stop market order was placed but it doesn't seem to be.

                          Any thoughts?

                          Thank you,

                          Nick

                          Comment


                            #14
                            Hello njmeyer713,

                            Thank you for your reply.

                            Can you provide an export of the script so I may test on my end to see what may be occurring? You can export it from Tools > Export > NinjaScript Addon. Do not check the box to export as a compiled assembly or I will not be able to review your logic. Please attach the resulting .Zip file to your reply.

                            Thanks in advance; I look forward to assisting you further.
                            Kate W.NinjaTrader Customer Service

                            Comment


                              #15
                              Kate-

                              I got it to work. Another entry's exit conditions was causing the variable to be true.

                              Another question for you, is it possible to have the stop trail the low of a series of candlesticks?

                              Basically once a trade goes 5o ticks in my favor, I want the trail to follow 25 ticks behind the lowest point from then onward until the stop is hit.

                              Something along the lines:

                              if (Profit = 50 ticks)

                              {
                              TrailBar = CurrentBar
                              TrailPrice = Low[All Bars since TrailBar]
                              FifteenTrailingStop= Exit short at Trail Price
                              }


                              I realize that the above code is not how to write it in C#, that is me simply putting some structure to my idea in plain english.

                              Hopefully it makes since.

                              Thank you,

                              Nick

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by WeyldFalcon, 08-07-2020, 06:13 AM
                              11 responses
                              1,421 views
                              0 likes
                              Last Post jculp
                              by jculp
                               
                              Started by RubenCazorla, Today, 09:07 AM
                              0 responses
                              1 view
                              0 likes
                              Last Post RubenCazorla  
                              Started by BarzTrading, Today, 07:25 AM
                              2 responses
                              29 views
                              1 like
                              Last Post BarzTrading  
                              Started by devatechnologies, 04-14-2024, 02:58 PM
                              3 responses
                              21 views
                              0 likes
                              Last Post NinjaTrader_BrandonH  
                              Started by tkaboris, Today, 08:01 AM
                              0 responses
                              6 views
                              0 likes
                              Last Post tkaboris  
                              Working...
                              X