Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Strategy still running after profit reached

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

    Strategy still running after profit reached

    ​Hello all, me again. Coming across a new issue with one of my strategies. I have a daily profit target of $300 - $500 on the strategy. When it hits the desired profit it is supposed to check it against the realized profit and if it is >= to profit then it is supposed to stop entering. My issue is that when the profit is reached it takes another trade and then doesn't close it until the end of session which leads to catastrophic losses or gains. Attachments for some clarification. Any help appreciated.

    Click image for larger version

Name:	profit.png
Views:	398
Size:	2.8 KB
ID:	1239698
    Click image for larger version

Name:	code.png
Views:	355
Size:	17.3 KB
ID:	1239699


    #2
    Hello sprks7979,

    Thanks for your note.

    To understand how a strategy is behaving and placing trades, debugging prints should be added to the script that print out each of the values being used in the condition(s) to place trades.

    In the strategy add prints (outside of any conditions) that print the values of every variable used in every condition that places an order along with the time of that bar.

    Prints will appear in the NinjaScript Output window (New > NinjaScript Output window).​

    Below is a link to a forum post that demonstrates how to use prints to understand behavior.
    https://ninjatrader.com/support/foru...121#post791121

    We also have a DailyLossLimit sample script you could view demonstrating how a daily limit would be made in a custom strategy. See the samples attached in the forum thread below.
    https://ninjatrader.com/support/foru...limit-examples

    Let us know if we may assist further.​
    <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

    Comment


      #3
      NinjaTrader_BrandonH Thanks for getting back to me and Im sorry it took me so long to get back. Is it possible to use prints in the builder? I am not a coder so I use the builder. Also, I tried using the DailyLossLimit example, I used the exact example and changed it from loss to profit and changed the example entry to a simple price cross,​ and it still takes trades after profit is reached. Could this be because it is a continuous strategy with no TP or SL? It just keeps flipping until it hits profit and then should stop. I will attach the strat in case it is needed. Attached is also a SS of the strat control panel. It hit $100 realized but still entered.
      Attached Files

      Comment


        #4
        Hello sprks7979,

        Thanks for your note.

        Yes, it is possible to use prints in the Strategy Builder to understand how a strategy is behaving.

        Please see the forum thread linked in post # 2 regarding how to use prints to understand behavior. In this forum thread, there is a demonstration video showing how to use prints in the Strategy Builder.

        Note that the video in the forum thread is called 'NT8 Strategy Builder'.

        I do not see anything standing out as incorrect in the script you shared. That said, debugging prints should be added to the script that prints out the DailyProfitLimit and DailyPnL to confirm how these values are evaulating in the script.

        That said, you could try adding a Profit Target and Stop Loss to your script to exit the entry order when the profit/stop is hit in the script. Otherwise, the strategy will flip orders from a long position to a short position until the Daily Profit Limit is hit as you stated.

        Note that the example script shared by Chelsea is only meant to be an example of how a Daily Loss Limit could be implemented, not a fully functioning out-of-the-box strategy.

        Please let me know if I may assist you further.
        <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

        Comment


          #5
          NinjaTrader_BrandonH Thanks for the help so far. I added prints and can see in the output window it is still taking trades after it hits the profit. No matter what I try it will always take at least 1 more trade. Normally this results in a win or a small loss but sometimes can be catastrophic. I will include the strat builder code and supporting screenshots. My not being a coder is probably playing against me but would like to be able to do this in the builder. It may be worth saying that this is happening in the analyzer and live strategies. When I load it directly to a chart after session close it does not show the extra trade.​

          Click image for larger version  Name:	notrade2.png Views:	0 Size:	9.8 KB ID:	1242543
          Last edited by sprks7979; 03-24-2023, 05:16 PM.

          Comment


            #6
            Hello sprks7979,

            Thanks for your note.

            I see that you are printing out TotalPnL, YesterdaysPnL, and DailyPNL in your script. However, I do not see where you are printing out the DailyProfit value in your script to see if the DailyProfit value is less than DailyProfit.

            The example script that I linked to in the forum thread linked on post # 2 compares if DailyPnL is > DailyLoss. Once the DailyPnL value is less than or equal to the DailyLoss value, no further trades will be placed.

            Please add prints to the script that prints out the DailyPnL value and DailyProfit value in your script to see how those two values compare in your script.

            For example, if your condition to place orders checks if the DailyPnL value is < DailyProfit, you could see in your prints when the DailyPnL value is actually evaluating to be greater than or equal to the DailyProfit value. In this example, no futher trades would be placed once the DailyPnL value is greater than or equal to DailyProfit.

            I look forward to assisting further.
            <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

            Comment


              #7
              Sorry to jump in here but its along the same topic. Everything with my strategy works except when it hits the daily profit, if there is any slippage and the profit is below the target by even a $5, the strategy with enter and exit in rapid fashion, like 6 or 7 trades in 2 to 3 seconds. This often turns a good day into a losing day, or at least costs a ton in fees. Has anyone else had this issue? I have included to portion of the code where it shows the daily profit/loss section, maybe someone can help?

              region Profit and Loss Check
              YesterdaysPNL[0] = YesterdaysPNL[1];
              StrategyTotallPNL[0] = SystemPerformance.AllTrades.TradesPerformance.Curr ency.CumProfit;

              if (Bars.IsFirstBarOfSession || firstSession)
              {
              firstSession = false;
              sessionIterator.GetNextSession(Time[0], true);
              YesterdaysPNL[0] = SystemPerformance.AllTrades.TradesPerformance.Curr ency.CumProfit;
              dailyPnL = 0;
              okToTrade = true;
              dailyPause = false;
              }

              else if (!Bars.IsFirstBarOfSession)
              {
              dailyPnL = StrategyTotallPNL[0] - YesterdaysPNL[0] + Position.GetUnrealizedProfitLoss(PerformanceUnit.C urrency, Close[0]);

              if (maxProfit == 0 && maxLoss == 0)
              {
              okToTrade = true;
              }

              else if (maxProfit == 0 && maxLoss > 0)
              {
              okToTrade = (dailyPnL > -System.Math.Abs(maxLoss)) ? true : false;
              }

              else if (maxProfit > 0 && maxLoss == 0)
              {
              okToTrade = (dailyPnL < maxProfit) ? true : false;
              }

              else if (maxProfit > 0 && maxLoss > 0)
              {
              okToTrade = ((dailyPnL > -System.Math.Abs(maxLoss)) && (dailyPnL < maxProfit)) ? true : false;
              }
              }

              if (maxProfit > 0 && dailyPnL >= maxProfit && !dailyPause)
              {
              if (showOutput) Print(State + " " + Time[0] + " " + Instrument.FullName + " Daily P&L: "
              + dailyPnL + " has met your session profit limit: " + maxProfit + " and the strategy has now been stopped.");
              dailyPause = true;
              }

              if (maxLoss > 0 && dailyPnL <= -System.Math.Abs(maxLoss) && !dailyPause)
              {
              if (showOutput) Print(State + " " + Time[0] + " " + Instrument.FullName + " Daily P&L: "
              + dailyPnL + " has met your session loss limit: " + maxLoss + " and the strategy has now been stopped.");
              dailyPause = true;
              }
              #endregion

              // add exits for when daily pnl limits hit
              if (Position.MarketPosition != MarketPosition.Flat && dailyPause)
              {
              if (Position.MarketPosition == MarketPosition.Long) ExitLong();
              if (Position.MarketPosition == MarketPosition.Short) ExitShort();
              if (showOutput) Print(Time[0] + " " + Instrument.FullName + " Position closed as session limit reached or close time reached");
              }
              ​​

              Comment


                #8
                Hello Steve4616,

                Thanks for your note.

                I do not see anything standing out specifically in the code you shared that would necessarily cause the behavior you are reporting.

                "profit is below the target by even a $5"

                To clarify, by the above comment you are stating that the dailPnL has not reached the limit (maxProfit) yet. Is that correct?

                If the dailyPnL has not reached the limit then the strategy would continue to place trades.

                Depending on the Calculate mode being used and how you are submitting your orders, the strategy may submit multiple orders if the condition to place the entry orders is true on each incoming tick.

                For example, if the condition to place the orders is remaining true and you are using Calculate.OnEachTick this could cause the script to place multiple orders as ticks are occurring.

                To understand exactly how your script is evaluating, you should further debug your script by adding prints to understand how it is behaving.

                In the strategy add prints (outside of any conditions) that print the values of every variable used in every condition that places an order along with the time of that bar. Also, print out the dailyPnL and maxProfit/maxLoss values to see how those are evaulating outside of the conditions as well.

                Below is a link to a forum post that demonstrates how to use prints to understand behavior.
                https://ninjatrader.com/support/foru...121#post791121
                <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

                Comment


                  #9
                  Thanks for your quick response Brandon. For the exit, if the daily target is $100, once the trade hit it, then it closes the trade by market order, so if the profit comes in at $90 or 95 after slippage from the market order, the strategy will place many trades within seconds. I have a video but can't upload it because its MP4. I think what I need is to have the daily target as the stop for a trade. But then, if the current profit is within say 10 or 20% of that target, then no trade. That would eliminate the re-entries, but I'm not sure if that's possible to code

                  Comment


                    #10
                    Hello Steve4616,

                    Thanks for your notes.

                    Since the daily target is at 90 or 95 instead of 100 this would mean that the daily target of 100 was not reached so the strategy could continue placing orders if the condition to do so is true.

                    You would need to come up with your own custom logic to offset your daily target by a certain percentage value and use that in your conditions.

                    If the limit is $100 then this would be simple to calculate the offset. 10 percent of $100 is $10. So you could consider creating an offset variable, dividing your dailytarget by say 10, and assigning that vlaue to your offset variable. Then offset your daily target by that variable.

                    double DailyTarget = 100;
                    double offset = DailyTarget/10;
                    Print(DailyTarget -offset);​ //this print would return a value of 90.


                    Note that it will ultimately be up to you to come up with the specific logic to accomplish your overall goals.
                    <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

                    Comment

                    Latest Posts

                    Collapse

                    Topics Statistics Last Post
                    Started by NullPointStrategies, Today, 05:17 AM
                    0 responses
                    24 views
                    0 likes
                    Last Post NullPointStrategies  
                    Started by argusthome, 03-08-2026, 10:06 AM
                    0 responses
                    120 views
                    0 likes
                    Last Post argusthome  
                    Started by NabilKhattabi, 03-06-2026, 11:18 AM
                    0 responses
                    63 views
                    0 likes
                    Last Post NabilKhattabi  
                    Started by Deep42, 03-06-2026, 12:28 AM
                    0 responses
                    41 views
                    0 likes
                    Last Post Deep42
                    by Deep42
                     
                    Started by TheRealMorford, 03-05-2026, 06:15 PM
                    0 responses
                    45 views
                    0 likes
                    Last Post TheRealMorford  
                    Working...
                    X