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

ForEx trading: Setting Stop Loss and Profit Targets by code not working

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

    ForEx trading: Setting Stop Loss and Profit Targets by code not working

    So, I am new to ForEx tradings and the seemingly prefered way to set a Profit Target or Stop Loss is using Pips.

    My Strategy sets the Stop Loss / Profit Target as shown below:
    SetProfitTarget(@"700", CalculationMode.Pips, 700);
    SetStopLoss(@"350", CalculationMode.Pips, 350, true);

    However when I look at the Executions, it stays in the trade until Exit on Session Close.

    Since this is clearly not what I want, how do I set it so that it will take effect?

    I am comfortable with setting these using either Price or Ticks, but Pips is new to me.
    Is there a way to get what the value of the Stop Loss/Profit Target is set to? At least that way
    I can verify what it is getting set to and see my problem.

    Thanks.

    #2
    In case anyone is wondering, I am entering the trades like this:

    EnterShort(iQtyToBuy, szOrderName);
    EnterLong(iQtyToBuy, szOrderName);

    So nothing fancy as far as that goes.

    Comment


      #3
      Hello ATMtrader0001,

      Thank you for your post.

      If you would like to see where your SetStopLoss() and SetProfitTarget() orders are, I recommend taking advantage of OnOrderUpdate() to get information about the orders that are placed, like in the example code at the bottom of this page:



      I went ahead and made a code example that makes an entry order and uses SetProfitTarget to set a 700 pip Profit Target. Per the help guide pages for SetStopLoss() and SetProfitTarget(), the stop loss orders have a signal name of "Stop loss" and profit target orders have "Profit target" as a signal name. Using that information, I was able to assign an order object and Print() information about the orders to the NinjaScript Output window. Here is the example:

      SetMethodValueExample_NT8.zip

      Using Print() statements can help you to understand your logic and debug/modify it as needed. My colleague has made the following post with more information about using prints and debugging scripts:



      Please let me know if I may be of further assistance.
      Emily C.NinjaTrader Customer Service

      Comment


        #4
        I did use the OnOrderUpdate to get information and it reported the Stop Loss as 0 even though it was set to 350 Pips.
        And I am quite familar how to use Print. I had done all this prior to posting so as not to waste time.

        So back to the question of how to properly set the StopLoss and ProfitTarget so that they will kick in rather than
        wait until Exit on session close to close out the position? Should I not use Pips? I thought that was the preferred
        method for Forex trading? It is frustrating that it enters the trade around 10 AM and even though it went past the
        Profit Target more than once it stayed in the trade.

        Comment


          #5
          Please verify my math.

          Here is the debug output:
          Profit target price: 0 Average Fill Price: 1.2861
          Stop loss price: 0 Average Fill Price: 1.2861

          You can see that using the code above there is not Stop Loss or Profit Target.

          In this case a trade goes in at 1.2861^0. With a Stop Loss at 350 pips and a Profit Target at 700 pip that would put the
          Profit Target at 1.2931^0 and the Stop Loss at 1.2826^0, or am I off in my calculation?

          Comment


            #6
            Hello ATMtrader0001,

            Thank you for your reply.

            You should be able to use pips for the calculation, there shouldn't be a need to change that. In my example from the previous reply, SetMethodValueExample_NT8, I used pips and was able to get a profit target as expected with the following logic:

            Here is the SetProfitTarget in State.Configure -

            HTML Code:
            else if (State == State.Configure)
            {
            SetProfitTarget("entryOrder", CalculationMode.Pips, 700);
            }
            Here is my logic in OnBarUpdate -

            HTML Code:
            protected override void OnBarUpdate()
            {
            if (State == State.Historical)
            return;
            if (Close[0] > Close[1])
            EnterLong("entryOrder");
            }

            Then I utilized OnOrderUpdate to assign the order objects and print order information -

            HTML Code:
            protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string nativeError)
            {
            if (order.Name == "entryOrder")
            entryOrder = order;
            
            else if (order.Name == "Profit target")
            profitTargetOrder = order;
            
            if (entryOrder != null && entryOrder == order)
            {
            Print(order.ToString());
            if (order.OrderState == OrderState.Filled)
            entryOrder = null;
            }
            
            if (profitTargetOrder != null && profitTargetOrder == order)
            {
            Print(order.ToString());
            if (order.OrderState == OrderState.Filled)
            profitTargetOrder = null;
            }
            }
            Is it possible that there is a disconnect with your entry signals used in the SetStopLoss() and SetProfitTarget() methods? I see for your entries you are using szOrderName as an entry signal. This entry signal would need to match the fromEntrySignal in the SetStopLoss() and SetProfitTarget() methods, although it appears that maybe you are using @"700" and @"300" for the fromEntrySignal. If the fromEntrySignal in the set methods is an empty string, it attaches the exit order to all entries, as mentioned in the help guide pages for these methods:




            Please try adjusting this parameter for fromEntrySignal and see if this helps to resolve the item and place your stop loss and profit target orders at the expected price.

            Thank you for your patience.
            Emily C.NinjaTrader Customer Service

            Comment


              #7
              It made no difference. I had changed that previously with no change.

              I adjusted the code to be this:

              EnterLong(iQtyToBuy, szOrderName);
              SetProfitTarget(szOrderName, CalculationMode.Pips, 200);
              SetStopLoss(szOrderName, CalculationMode.Pips, 100, true);

              I adjusted the StopLoss/ProfitTarget to be more likely to hit it.

              In my Backtest it entered in a trade at 1.0023^5 and it stayed in the trade until "Exit on session close" at 1.0051^6.
              If my math is correct that is 281 pips. Correct??

              All twenty of my trades in the Backtest resulted in Exit on session close using pips.

              If I change the code above from Pips to Ticks, those same twenty trades hit the StopLoss and ProfitTarget as expected.

              That puts us back to the code not setting the StopLoss/ProfitTarget correctly when using Pips. Or is my math off and pips have
              a higher value than ticks.

              Again, I am using Pips as I thought that was the preferred method in Forex trading.

              Comment


                #8
                Hello ATMtrader0001,

                Thank you for your reply.

                Depending on the instrument you are using in your backtest, the price is likely not hitting your profit target and stop loss (even set at 200 and 100 ticks). The difference between the entry of 1.0023^5 and the exit of 1.0051^6 is 28.1 pips. I apologize I did not answer your math question in your previous post - I was aiming to address why the Profit target price and Stop loss price were printing as 0.
                In order to help visualize the distance in pips, you could open a chart with the Chart Trader and set up an ATM strategy with the Stop Loss and Profit Target in pips. Next, place a market entry in a simulation account and you will see the order flags for the Stop Loss and Profit Target orders and you can visually compare them with the entry price. This may help, as well as the following section of the help guide:


                Although this is not related to NinjaScript strategies, some of the concepts in the Forex 101 webinar may be useful as well:


                With that in mind, you may need to adjust the value used for your Stop Loss and Profit Target orders in the strategy in order to see those prices hit in your backtest. Again, this will depend on the instrument and timeframe used in your backtest.

                Please let us know if we may be of further assistance.
                Emily C.NinjaTrader Customer Service

                Comment


                  #9
                  Last response.

                  Based on that math then, why did the StopLoss/ProfitTarget work when set to Ticks and not Pips? Shouldn't the calculation be the same?
                  Or is the 28.1 Pips actually 281 Ticks?

                  Comment


                    #10
                    Hello ATMtrader0001,

                    Thank you for your reply.

                    As mentioned in the help guide link I sent, 1 pip = 10 ticks. 28.1 pips is the equivalent of 281 ticks. If you have a tick value, to get the number of pips you divide by 10.

                    I hope this helps to clarify and address your inquiry. Please don't hesitate to reach out with any additional questions or concerns.
                    Emily C.NinjaTrader Customer Service

                    Comment

                    Latest Posts

                    Collapse

                    Topics Statistics Last Post
                    Started by rayyyu12, Today, 12:47 AM
                    0 responses
                    4 views
                    0 likes
                    Last Post rayyyu12  
                    Started by ETFVoyageur, 05-07-2024, 07:05 PM
                    17 responses
                    135 views
                    0 likes
                    Last Post ETFVoyageur  
                    Started by ETFVoyageur, Yesterday, 10:13 PM
                    1 response
                    10 views
                    0 likes
                    Last Post ETFVoyageur  
                    Started by somethingcomplex, Yesterday, 10:36 PM
                    0 responses
                    9 views
                    0 likes
                    Last Post somethingcomplex  
                    Started by sofortune, 05-10-2024, 10:28 AM
                    5 responses
                    22 views
                    0 likes
                    Last Post sofortune  
                    Working...
                    X