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

Trailing Stop to add to my script

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

    Trailing Stop to add to my script

    Hi there,

    I need some help. I am not a coder. I have a script developed using Strategy builder and I am satisfied with the result but I need to add Trailing Stop with some options and I want it to work this way :

    1 - Trade is placed with a Stop Loss and Profit Target first.
    2 - When trade moves in profit by X tick let's say 20 ticks > Stop loss is moved to Y above break even ( break even + # of ticks)
    3- From there it will move by Z tick , let 's say by 5 ticks for each X1 tick , basically the way it work in the ATM
    Or the other option will be : to call a pre programmed strategy/ Trailing Stop from the ATM.

    I want to be able to unlock and add ( copy and and paste) into to Editor
    And please let me know where exactly I will paste it.

    Thanks and Kind Regards.
    Adiano

    #2
    Hello Adiano,

    A trailing stop (SetTrailStop) cannot be programmed in this manner. A trailing stop trails tick for tick.

    You can use an exit order and modify the price of this to code any logic you would like.

    Below are links to a few examples.
    https://ninjatrader.com/support/foru...427#post527427
    https://ninjatrader.com/support/foru...345#post521345
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Originally posted by NinjaTrader_ChelseaB View Post
      Hello Adiano,

      A trailing stop (SetTrailStop) cannot be programmed in this manner. A trailing stop trails tick for tick.

      You can use an exit order and modify the price of this to code any logic you would like.

      Below are links to a few examples.
      https://ninjatrader.com/support/foru...427#post527427
      https://ninjatrader.com/support/foru...345#post521345
      Chelsea , thanks for the info. I just need few more clarifications before I can look for someone to do this for me as I have very limited knowledge of programming. I looked at the examples by downloading and installing the script/ examples but I didn't have any idea how to insert them in my script.
      Anyway here are my questions :
      1- From a script developed using the strategy builder/ the Editor is there a way of pointing & calling a custom template saved using the ATM. Let 's say you created a ProfitTarget/ stop loss & trailing stop from the ATM.
      2- Using the editor can someone program the exact way , trailing stop is handled using the ATM.
      Thanks.
      Adiano

      Comment


        #4
        Hello akitenge,

        Using the Strategy Builder it would not be possible to use Atm Strategy Methods and submit an order with a saved Atm Strategy Template.

        The script must be unlocked and coded by hand.

        Below is a public link to the help guide on Atm Strategies.
        https://ninjatrader.com/support/help...gy_methods.htm


        However, it likely would be possible to custom code the logic for trailing actions using the Strategy Builder and Exit orders.


        The examples I have provided are not something you can insert into another script. These are examples that demonstrate how to do something. These are for you to learn from and model your code after.

        Below is a public link to a forum post with helpful information about getting started with NinjaScript.
        http://ninjatrader.com/support/forum...609#post503609

        You can also contact a professional NinjaScript Consultant who would be eager to create or modify this script at your request or assist you with your script. The NinjaTrader Ecosystem has affiliate contacts who provide educational as well as consulting services. Please let me know if you would like our business development follow up with you with a list of affiliate consultants who would be happy to create this script or any others at your request.
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          Hi Chelsea,

          Can you please take a look at this code? The idea is for the stop to move every 5 ticks. But right now the stop does not move past 40. I've also attached the output from the script.

          I tried to model it after the sample price modification example.

          Thanks for your time.

          Attached Files

          Comment


            #6
            Hello howardtrade,

            As a tip, to export a NinjaTrader 8 NinjaScript so this can be shared and imported by the recipient do the following:
            1. Click Tools -> Export -> NinjaScript...
            2. Click the 'add' link -> check the box(es) for the script(s) and reference(s) you want to include
            3. Click the 'Export' button
            4. Enter a unique name for the file in the value for 'File name:'
            5. Choose a save location -> click Save
            6. Click OK to clear the export location message
            By default your exported file will be in the following location:
            • (My) Documents/NinjaTrader 8/bin/Custom/ExportNinjaScript/<export_file_name.zip>
            Below is a link to the help guide on Exporting NinjaScripts.
            http://ninjatrader.com/support/helpG...-us/export.htm


            Below is a link to an example of trailing logic.
            https://ninjatrader.com/support/foru...269#post802269


            Use prints to understand the behavior.

            You feel the condition is not being evaluated as true is this correct?
            if (Close[0] > Position.AveragePrice + (30 * (TickSize / 2))
            && (Close[0] < Position.AveragePrice + (40 * (TickSize / 2))))

            Print the time of the bar, Close[0], and Position.AveragePrice + (30 * (TickSize / 2) to the output window.
            Comment out all prints that are not for this specific condition.
            Save the output to a text file and include this with your next post.

            Below is a link to a forum post that demonstrates how to use prints to understand behavior.
            ​​​​​​​https://ninjatrader.com/support/foru...121#post791121
            Last edited by NinjaTrader_ChelseaB; 04-25-2021, 09:06 PM.
            Chelsea B.NinjaTrader Customer Service

            Comment


              #7
              Hi Chelsea,

              Thanks for the response and for the tip on exporting scripts. I will keep that in mind for the future.

              Please see the requested print output attached. Just a heads up, I removed large sections of the redundant trace below, just to compress the file size.


              2008-01-22 6:21:00 AM Strategy 'v3BadSMA10/-1': Entered internal SetStopTarget() method: Type=Stop FromEntrySignal='Long1' Mode=Ticks Value=50 IsSimulatedStop=False IsMarketIfTouched=False
              2008-01-22 6:21:00 AM Strategy 'v3BadSMA10/-1': Entered internal SetStopTarget() method: Type=Stop FromEntrySignal='Long2' Mode=Ticks Value=50 IsSimulatedStop=False IsMarketIfTouched=False
              2008-01-22 6:21:00 AM Strategy 'v3BadSMA10/-1': Entered internal SetStopTarget() method: Type=Stop FromEntrySignal='Long3' Mode=Ticks Value=50 IsSimulatedStop=False IsMarketIfTouched=False
              2008-01-22 9:42:00 AM Strategy 'v3BadSMA10/-1': Entered internal SetStopTarget() method: Type=Stop FromEntrySignal='Short1' Mode=Ticks Value=50 IsSimulatedStop=False IsMarketIfTouched=False
              2008-01-22 9:42:00 AM Strategy 'v3BadSMA10/-1': Entered internal SetStopTarget() method: Type=Stop FromEntrySignal='Short2' Mode=Ticks Value=50 IsSimulatedStop=False IsMarketIfTouched=False
              2008-01-22 9:42:00 AM Strategy 'v3BadSMA10/-1': Entered internal SetStopTarget() method: Type=Stop FromEntrySignal='Short3' Mode=Ticks Value=50 IsSimulatedStop=False IsMarketIfTouched=False
              Attached Files

              Comment


                #8
                Hello howardtrade,

                Just to assist with creating a print that follows the pattern of the video and example print I have linked in post #6, that prints exactly what is in the condition with labels for the values and comparison operators.
                This would be printed outside of any conditions so that we may see when the value is true and when it is not true.
                (edited to remove the comparison and provide the value)
                Code:
                Print(string.Format( "{0} | Close[0]: {1} > Position.AveragePrice: {2} + (30 * (TickSize: {3} / 2): {4}) && (Close[0]: {1} < Position.AveragePrice: {2} + (40 * (TickSize: {3} / 2): {5}))", Time[0], Close[0], Position.AveragePrice, TickSize, Position.AveragePrice + (30 * (TickSize / 2)), Position.AveragePrice + (40 * (TickSize / 2)) ));
                Within the condition you might have a print that just prints which condition set this is that is true.
                Code:
                Print(string.Format("{0} | SetStopLoss called with Position.AveragePrice - 40 * TickSize: {1}", Time[0], Position.AveragePrice - 40 * TickSize));

                In the output you have provided, I'm not exactly sure what is in the print, but the price printed appears to be 10,000 larger than where the stop was previously working.

                2008-01-22 10:46:00 AM Strategy 'v3BadSMA10/-1': Entered internal SetStopTarget() method: Type=Stop FromEntrySignal='Long3' Mode=Price Value=1080.25 IsSimulatedStop=False IsMarketIfTouched=False

                Position Average Price + 30 * TickSize / 2 is 10893.75
                Last edited by NinjaTrader_ChelseaB; 04-27-2021, 11:09 AM.
                Chelsea B.NinjaTrader Customer Service

                Comment


                  #9
                  Hi Chelsea,

                  In post #6 you asked for..
                  Print the time of the bar, Close[0], and Position.AveragePrice + (30 * (TickSize / 2) to the output window.
                  Comment out all prints that are not for this specific condition.

                  the print in the output is from Position.AveragePrice + (30 * (TickSize / 2)


                  Attached is a trailing stop practice script and the output from the prints you requested. I hope I've done them correctly.
                  Attached Files

                  Comment


                    #10
                    Hello howardtrade,

                    Please enable TraceOrders so that we can see when orders are being submitted and when set methods are being updated. I have directed to comment out all other calls to Print(), however, I have not advised to disable TraceOrders.

                    The print, I was copying and pasting and overlooked the comparison was returning a bool and not the calculated value. The print above in post #8 is corrected.

                    For the output so far, even without the, it does appear this specific condition is evaluating as true at some times.

                    2008-01-22 7:38:00 AM | Close[0]: 1061 > Position.AveragePrice: 1057.5 + (30 * (TickSize: 0.25 / 2): False) && (Close[0]: 1061 < Position.AveragePrice: 1057.5 + (40 * (TickSize: 0.25 / 2): True))
                    2008-01-22 7:38:00 AM | SetStopLoss called with Position.AveragePrice - 40 * TickSize: 1047.5

                    As the Close[0] is 1061 and the position is long, I would expect the stop loss to be moved to 1047.5. Without the TraceOrders enabled, we cannot confirm this was performed.


                    As the movement conditions are only called when long, the print of the condition set we are diagnosing can within the else if that checks the position is long. This would prevent prints when the position is flat to reduce the amount of prints.
                    Code:
                    ...
                    else if (Position.MarketPosition == MarketPosition.Long)
                    {
                    Print(string.Format( "{0} | Close[0]: {1} > Position.AveragePrice: {2} + (30 * (TickSize: {3} / 2): {4}) && (Close[0]: {1} < Position.AveragePrice: {2} + (40 * (TickSize: {3} / 2): {5}))", Time[0], Close[0], Position.AveragePrice, TickSize, Position.AveragePrice + (30 * (TickSize / 2)), Position.AveragePrice + (40 * (TickSize / 2)) ));
                    ...

                    The export you have provided is a dll assembly. By checking 'Export as compiled assembly' the code when exporting, it will not be open source and no one will be able to see your code. Checking 'Export as compiled assembly' is not in the steps I have provided in post #6.
                    Chelsea B.NinjaTrader Customer Service

                    Comment


                      #11
                      Hey thanks for your patience. This is clearly an area I struggle with.
                      Hopefully these outputs and prints and zip file are all correct.
                      Attached Files

                      Comment


                        #12
                        Hello howardtrade,

                        Thank you for providing this output.
                        It does appear the orders are getting updated.

                        Before:
                        2008-01-22 7:37:00 AM Strategy 'Trailstoppractice/-1': Entered internal SetStopTarget() method: Type=Stop FromEntrySignal='Short3' Mode=Ticks Value=50 IsSimulatedStop=False IsMarketIfTouched=False
                        The condition is true:
                        2008-01-22 7:38:00 AM | Close[0]: 1061 > Position.AveragePrice: 1057.5 + (30 * (TickSize: 0.25 / 2): 1061.25) && (Close[0]: 1061 < Position.AveragePrice: 1057.5 + (40 * (TickSize: 0.25 / 2): 1062.5))
                        After the SetStopTarget is submitted as 1047.5:
                        2008-01-22 7:38:00 AM Strategy 'Trailstoppractice/-1': Amended stop order orderId='NT-00011-60522' account='Backtest' name='Stop loss' orderState=Working instrument='ES 06-21' orderAction=Sell orderType='Stop Market' limitPrice=0 stopPrice=1045 quantity=1 tif=Gtc oco='NT-00008-60522' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2008-01-22 07:37:00' gtd='2099-12-01' statementDate='2021-04-27'
                        2008-01-22 7:39:00 AM Strategy 'Trailstoppractice/-1': Entered internal SetStopTarget() method: Type=Stop FromEntrySignal='Long3' Mode=Price Value=1047.5 IsSimulatedStop=False IsMarketIfTouched=False
                        2008-01-22 7:39:00 AM | SetStopLoss called with Position.AveragePrice - 40 * TickSize: 1047.5

                        Is there a specific time you feel the condition was true but the order was not updated to a new price?
                        Chelsea B.NinjaTrader Customer Service

                        Comment


                          #13
                          Thanks Chelsea,

                          So I think I understand the logic and yes, you're correct. The code is working, but perhaps not accomplishing what I was trying to do.

                          What I'm trying to avoid is the close being a few ticks away from my target and then giving up 50 ticks in profit because of a trailing stop. But I see now that as price moves away from my target, each set of conditions becomes true again so the stop is actually moving backwards. I hope that makes sense over text.

                          How can I code this so that I'm not losing so much simply because the close didn't quite reach the profit target?

                          Comment


                            #14
                            Hello howardtrade,

                            Which condition is evaluating as true when you are not expecting?

                            Why are you not expecting that condition to be true at that time?

                            Have you examined the ProfitChaseStopTrailSetMethodsExample_NT8 linked in post #6 that is a working example of trailing logic using Set methods?
                            Chelsea B.NinjaTrader Customer Service

                            Comment


                              #15
                              Hi Chelsea,

                              I fixed my issue. Thanks for your help.

                              I added a condition to make sure the stop won't move backwards

                              Code:
                              (Close[1] > Position.AveragePrice - (10 * (TickSize / 2)))
                              I took a look at those profit chase stop examples but they're over my head for programming.

                              If any other beginners are interested, here's the code. Basically once the price gets within 20 ticks of the target, the trailing stop gets reduced from 50 to 25.
                              Attached Files

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by mattdowns1234, Today, 06:57 PM
                              0 responses
                              14 views
                              0 likes
                              Last Post mattdowns1234  
                              Started by dgee949, Today, 06:26 PM
                              0 responses
                              24 views
                              0 likes
                              Last Post dgee949
                              by dgee949
                               
                              Started by dgee949, Today, 05:58 PM
                              0 responses
                              30 views
                              0 likes
                              Last Post dgee949
                              by dgee949
                               
                              Started by thepcmd, Today, 05:14 PM
                              0 responses
                              34 views
                              0 likes
                              Last Post thepcmd
                              by thepcmd
                               
                              Started by xmess777, Today, 04:58 PM
                              0 responses
                              23 views
                              0 likes
                              Last Post xmess777  
                              Working...
                              X