Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

NinjaScript - Modifying Active Positions with a manual Stop Loss Strategy

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

    NinjaScript - Modifying Active Positions with a manual Stop Loss Strategy

    Hello,

    I want to develop using ninja script a stop loss strategy, however I am struggling to understand even after looking through other forum posts and tutorials how to achieve what I want,

    An example of what I want to do is:

    1) On a Long entry signal create a market order with a stop loss of 1%
    2) If that position goes above 2% profit then I want to enable a trailing stop loss at 0.5%

    The things I am struggling with are how to identify the open positions profit and how can I set the stop loss for that position?

    Thank you In advance, please let me know if you need any more details to help me!

    #2
    Hello MrHump,

    Thank you for your note.

    We have a reference sample that demonstrates modifying the price for stop loss and profit target orders here:


    That example uses a number of ticks as a trigger for breakeven and not a percentage of profit. What do you mean by a stop loss of 1%? Are you referring to 1% of your account value? Then the 2% of what will trigger the trailing stop loss?

    You could get a position's unrealized profit/loss with GetUnrealizedProfitLoss():


    I look forward to your clarification.

    Comment


      #3
      Hi NinjaTrader_Emily​,

      Thank you for the fast response!

      So in my example I want to open the position with the initial stop loss set at 1% of the entry price for that market order,
      e.g SetStopLoss(CalculationMode.Percentage, 0.01)

      Then if the position hits a take profit level of 2% of the initial entry price I want to then set a trailing stop loss
      e.g
      if(Position.GetUnrealizedProfitLoss() > 2%)
      then SetTrailingStopLoss(CalculationMode.Percentage, 0.005)

      However I have read that I can't use these methods together as SetStopLoss() will overwrite the SetTrailingStopLoss() method, if this is the case then is there a way to manually set the stop loss value on a position
      e.g
      Position.StopLoss = Close[0] - 0.05%

      Comment


        #4
        Hello MrHump,

        Thank you for clarifying.

        It is correct that you wouldn't be able to combine SetStopLoss() and SetTrailStop(). That said, you may change the price using SetStopLoss() by calling it dynamically in OnBarUpdate(). In the reference sample I linked, the stop loss is initially set to the value of StopLossTicks (in your case, you would set the CalculationMode to CalculationMode.Percent with .01):
        Code:
                    if (Position.MarketPosition == MarketPosition.Flat)
                    {
                        SetStopLoss(CalculationMode.Ticks, StopLossTicks);
                    }
        ​
        Then, when the price is greater than the entry price (Position.AveragePrice) by 50 ticks, the stop loss moves to breakeven:
        Code:
                    // 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+50 ticks, set stop loss to breakeven
                        if (Close[0] > Position.AveragePrice + 50 * TickSize)
                        {
                            SetStopLoss(CalculationMode.Price, Position.AveragePrice);
                        }
                    }
        ​
        In your case, you could check if the Close[0] is greater than Position.AveragePrice plus or minus (depending on if you are short or long) (.02 * Position.AveragePrice) to get the entry price plus/minus 2% of the entry price. If that condition is met, you could call SetStopLoss() again to modify your stop loss to the desired value. Ultimately, you may need to save the Close[0] to a double variable and only modify your stop price if the new Close[0] is in a greater profitable direction than the saved variable; that way the stop loss will only trail as the price moves in your favor and will stay put if the price moves against you.

        Please let me know if you have any additional questions or concerns.

        Comment


          #5
          That is perfect thank you very much I plan on trialing this today, I didn't realize that Position.AveragePrice was the way to get the entry price of a position!

          Would you recommend using Position.AveragePrice

          Close[0] > Position.AveragePrice + Position.AveragePrice * 0.02

          or the GetUnrealizedProfitLoss()

          Close[0] > GetUnrealizedProfitLoss(PerformanceUnit.Percent, 0.02)
          Last edited by MrHump; 08-19-2023, 04:42 AM.

          Comment


            #6
            Hello MrHump,

            Thank you for your reply.

            Which one to use would be up to you, though your use of GetUnrealizedProfitLoss() does not quite make logical sense with what you wrote.

            This statement checks if the last close price is greater than the entry price plus 2% of the entry price:
            Close[0] > Position.AveragePrice + Position.AveragePrice * 0.02

            This statement would check if the last close price is greater than the unrealized PnL value; this does not make sense, as the price value would not be similar to a PnL value:
            Close[0] > GetUnrealizedProfitLoss(PerformanceUnit.Percent, 0.02)

            GetUnrealizedProfitLoss() returns a double value that represents the account's unrealized PnL. A comparison with the last close price does not make logical sense.

            I suggest adding print statements that include each value to better understand the script's behavior and how each value is calculated throughout your script:


            Thank you for your time and patience.

            Comment


              #7
              I wanted to do the same but with several positions.
              How to know the pnl of a position.
              Since I cannot use GetUnrealizedProfitLoss() because this refers to the total of the positions, not to a specific one.

              Jose Donet.

              Comment


                #8
                Originally posted by Lesclafit View Post
                I wanted to do the same but with several positions.
                How to know the pnl of a position.
                Since I cannot use GetUnrealizedProfitLoss() because this refers to the total of the positions, not to a specific one.

                Jose Donet.
                Hello Jose,

                Thank you for your reply.

                GetUnrealizedProfitLoss() still comes from a position object. If you have a strategy that submits orders to multiple instruments, it would use the positions array. You could then get the unrealized PnL for a specific position in the array or use a BarsInProgress filter in OnBarUpdate() to get information from a specific instrument's position:For more information, please see the section "Entering, Exiting and Retrieving Position Information" at the bottom of the following page:Please let us know if we may be of further assistance.

                Comment


                  #9
                  Hello again, thanks for the answer.
                  What I want is to know the Pnl of several positions of the same strategy in the same symbol.
                  Thanks
                  Jose Donet​

                  Comment


                    #10
                    Hello Jose,

                    Thank you for your reply.

                    Your strategy can only hold a long, short, or flat position for the same symbol. Are you referring to scaling in/out of a position for the same instrument? As in adding and removing additional contracts to the same open position? Please provide an example of what you are looking to achieve so I may better assist you.

                    I look forward to your reply.

                    Comment


                      #11

                      Hello again.

                      Yes, the same strategy has several contracts at different prices, in the same direction, in the same market, and I want to manage the independent position,
                      what I wanted to use is the Pnl to manage a position that when I have made 50% of the Profit that will be placed in Breakeben.
                      I managed to do it but in one position, I did not prove if it worked with the strategy with two positions at different prices but
                      I suppose that since the Pnl is for the entire position it is not worth it.

                      Thanks.

                      if (( Position.GetUnrealizedProfitLoss(PerformanceUnit.T icks, Close[0])>(Tp_3_TICKS/2)))
                      {
                      /

                      SetStopLoss("PicMV_L_3", CalculationMode.Price, Position.AveragePrice,false);
                      }
                      else if (Position.MarketPosition == MarketPosition.Flat)
                      SetStopLoss("PicMV_L_3", CalculationMode.Ticks, STOP_3_TICKS, false);

                      ​

                      Last edited by Lesclafit; 08-21-2023, 11:33 AM.

                      Comment


                        #12
                        Hello Jose,

                        Thank you for your reply.

                        The Position.AveragePrice is the average price of a position based on the fill prices and quantity. If you want to track the PnL for multiple contracts that were entered in the same direction at different prices, you could create double variables to hold the value of the execution price when each additional contract in the position was filled. Then, you could calculate the difference between the current price and the fill price from each execution to get the PnL for each separate entry price.
                        Please let us know if we may be of further assistance.

                        Comment


                          #13
                          Hi Again!

                          It looks like when I am updating my stop loss it is producing weird results for example I initially set the stop loss to 0.02% Which works correctly

                          and then the profit hits above 0.02% I want to update the stop loss to be trailing at 0.01% however when I calculate the new stop loss price and update the stop loss it doesn't update to the correct value!

                          entry price: 4370
                          initial stop loss: 4282.6
                          When close hits: 4457.4
                          then new trailing stop loss: 4412.82

                          However on setting the new trailing stop loss with that value using the code below, it is actually setting the stop loss to 3482.75 which seems really random and very far off the number I am providing it!

                          SetStopLoss(CalculationMode.Currency, 4412.82);

                          Any help is appreciated again

                          Comment


                            #14
                            Hello MrHump,

                            Thank you for your reply.

                            Have you tried adding any print statements to understand the values being used? If so, what are the results of the print statements?
                            Another thing to note is that the CalculationMode.Currency is described as, "PnL away from average entry. Calculated by the dollar per tick value for the order quantity used." This means that you would put the desired PnL value for the value, such as 100 if you want the stop loss to be at $100 of loss away from the entry based on the dollar per tick value.

                            Are you instead trying to set the stop loss to a calculated price value? If that is the case, you should use CalculationMode.Price which will set the stop to the absolute price point specified. The different calculation modes are explained on the help guide page:


                            Please let me know if I may be of further assistance.

                            Comment


                              #15
                              Hey NinjaTrader_Emily​,

                              That is exactly what I was doing, using CalculationMode.Price worked perfectly!

                              Thank you again!

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by NullPointStrategies, Yesterday, 05:17 AM
                              0 responses
                              62 views
                              0 likes
                              Last Post NullPointStrategies  
                              Started by argusthome, 03-08-2026, 10:06 AM
                              0 responses
                              134 views
                              0 likes
                              Last Post argusthome  
                              Started by NabilKhattabi, 03-06-2026, 11:18 AM
                              0 responses
                              75 views
                              0 likes
                              Last Post NabilKhattabi  
                              Started by Deep42, 03-06-2026, 12:28 AM
                              0 responses
                              45 views
                              0 likes
                              Last Post Deep42
                              by Deep42
                               
                              Started by TheRealMorford, 03-05-2026, 06:15 PM
                              0 responses
                              50 views
                              0 likes
                              Last Post TheRealMorford  
                              Working...
                              X