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

Daily profit target

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

    Daily profit target

    Is it possible to have both a daily profit target in terms of $ amount as well as a weekly profit target?
    i.e. if my daily target is say 500$ and my weekly target is 1200$. I currently have a daily profit/loss code that resets to zero at the end of day, but I was wondering if I could have that days net amount added to a running pnl as well and have a bool for that Weekly total? Would I need to use a series for this?

    #2
    Could you show your NinjaScript code for daily loss calculation, please?

    I tried "Performance.AllTrades.TradesPerformance.GrossLoss ", but it's a value from Start of the strategy (not a single day)

    Comment


      #3
      Hello adrew99,

      Yes this is likely possible, it sounds like what you have now is similar to what you would need for a weekly running value. Mainly you would just not reset the value until you wanted to such as the first day of the week. If you are using the collections your strategy inherits to calculate the value, these should be retained as long as the strategy is running so you can use the total statistics from when it started. We have a sample demonstrating resetting daily in the following link, you could likely use this as a starting point and move to weekly checks. https://ninjatrader.com/support/help...nce_statis.htm

      I look forward to being of further assistance.

      JesseNinjaTrader Customer Service

      Comment


        #4
        I am by no means a coder, so please take my ugly coding with a grain of salt.

        public class XXXXXXXXX : Strategy
        {
        private bool DayIsOk;
        private double Accumulated;
        private double Profit = 600;
        private double Loss = 500;
        private DateTime reset_time;






        protected override void OnStateChange()
        {
        if (State == State.SetDefaults)
        {

        // Disable this property for performance gains in Strategy Analyzer optimizations
        // See the Help Guide for additional information
        IsInstantiatedOnEachOptimizationIteration = true;
        Profit = Max_Profit;
        Loss = Max_Loss;


        DayIsOk = true;
        Accumulated = 0;
        reset_time = DateTime.Parse("00:05", System.Globalization.CultureInfo.InvariantCulture) ; //resets the daily profit to zero at 12:05AM



        else if (State == State.Configure)



        protected override void OnBarUpdate()
        {
        if (BarsInProgress != 0)
        return;

        if (CurrentBars[0] < 15 )
        return;


        // Short Requirement
        if ((CrossBelow(GetCurrentAsk(0), Low, 12))

        other market conditions go here.

        //Daily Profit - this goes at the end of those conditions before the entry order
        && (DayIsOk == true))


        // Long requirement

        if ((CrossAbove(GetCurrentBid(0), High, 12))


        other market conditions go here,

        //Daily Profit - This goes at the end of those conditions before the entry order
        && (DayIsOk == true))




        // All target and stop info would go here,



        // conditions for max profit and loss calculations
        if ((SystemPerformance.AllTrades.TradesPerformance.Cu rrency.CumProfit - Accumulated > Max_Profit)
        || (SystemPerformance.AllTrades.TradesPerformance.Cur rency.CumProfit - Accumulated < -Max_Loss))

        {
        DayIsOk = false;
        }

        // Reset daily profit to zero
        if (Times[0][0].TimeOfDay < reset_time.TimeOfDay)
        {
        DayIsOk = true;
        Accumulated = SystemPerformance.AllTrades.TradesPerformance.Curr ency.CumProfit;

        }
        }

        There was a Youtube video that i followed and was able to add the coding. He used the wizard to build, but towards the end showed the code, which is what i followed. I cant seem to locate the video now, but if i do i will post.

        Comment


          #5
          Thanks Jesse, But the problem I have is I want to have both instances running. What I mean by this is, I want to have a daily profit/loss as well as a weekly profit/loss.
          I already know how to stop my strategy from trading based on the daily profit and have it reset to zero at the end of the day. My issue is how can I store Monday's profit/loss, and add Tuesdays profit/loss to that while still reseting Tuesdays profit to Zero at the end of the day? i.e. add Tuesdays pnl to Mondays. add Wednesdays pnl to the combined (Monday & Tuesday) and so on.

          I was thinking I could use a series to count the cumprofit at an instance at a designated time before the reset is accomplished or something similar.

          If you've noticed my code above, you'll see im not a coder by any means, so please bare with me with.
          Thanks

          Comment


            #6
            Hello,
            Thank you for the reply.

            But the problem I have is I want to have both instances running. What I mean by this is, I want to have a daily profit/loss as well as a weekly profit/loss.
            This is what I had provided an explanation for. If you wanted to add an additional total, you can add that, it would be in addition to what you have now. The syntax you provided is resetting daily, if you wanted to do a weekly reset you would essentially need to recreate what you have done for the daily reset but do it once a week instead.

            My issue is how can I store Monday's profit/loss, and add Tuesdays profit/loss to that while still reseting Tuesdays profit to Zero at the end of the day?
            You can likely add this logic in the condition you have now if you want to do the accumulation during each days reset.


            For example:

            Code:
            private double WeeklyAccumulated;
            
            
            Accumulated = SystemPerformance.AllTrades.TradesPerformance.Curr ency.CumProfit;
            WeeklyAccumulated += Accumulated;

            In a separate condition to reset weekly, you can then reset this to 0; This would need to go before where you accumulate the value so this resets before you start accumulating again for the first day.

            Code:
            if (Time[0].DayOfWeek == DayOfWeek.Monday)
            {
                WeeklyAccumulated = 0;
            }

            I look forward to being of further assistance.
            JesseNinjaTrader Customer Service

            Comment


              #7
              Hi There.

              I'm trying to come back to this after a few months since I was never able to get this weekly profit/loss limit to work. I can't seem to understand where to place the code.
              I think may have the wrong thinking when it comes to this. In my mind, what im asking this to do is add each prior days accumulated to the current pnl minus the weekly profit targets I have in place.
              if (accumulated - systemperformance. alltrades.tradesperformance.currency.cumprofit - (weekly target as a digit i.e. 1000))

              My current code has the above in it, however if I put the weekly before the daily, it only stops trading when weekly numbers are hit.
              If I put it after, the uses the daily limit and never the weekly.

              Hopefully you can help explain this as tho your talking to a 6 year old, because that what my brain feels like with this one.




              Comment


                #8
                Hello adrew99,

                Thank you for the reply.

                So that I can understand where you are at now, can you provide the updated code that you are referring to here?

                If the case is that moving one condition before the other is causing it to not work as expected, that may be a situation to use the or operator and join the conditions. Seeing the conditions as you have them should help determine if that would be needed or not.


                I look forward to being of further assistance.
                JesseNinjaTrader Customer Service

                Comment


                  #9
                  Hi Jesse,
                  Thank you for the reply.

                  Bellow is the code, as i've understood it from your posts above. Like i said, i must not be placing them in the correct positions.

                  In the public class i have the following;

                  Code:
                  private bool DayIsOk;
                          private bool WeekIsOk;
                          private double Accumulated;
                          private double DailyAccumulated;
                          private double WeeklyAccumulated;
                          private double Profit = 550;
                          private double Loss = 450;
                          private double WeeklyProfit = 1200;
                          private double WeeklyLoss = 1200;
                          private DateTime reset_time;
                  
                          private bool printOneTime = true;
                          private bool weeklyprintonetime = true;

                  in protection override void:
                  Code:
                  Profit = Max_Profit;
                                  Loss = Max_Loss;
                  
                                  WeeklyProfit = Weekly_Profit;
                                  WeeklyLoss = Weekly_Loss;
                  
                  
                                  // reset time for daily profit_loss
                              DayIsOk        = true;
                                  WeekIsOk    = true;
                                  Accumulated    = 0;
                                  DailyAccumulated = 0;
                                  WeeklyAccumulated += Accumulated;
                  
                                  reset_time = DateTime.Parse("00:05", System.Globalization.CultureInfo.InvariantCulture);
                  Then in the trade conditions, i have the following If's
                  Code:
                      //Daily Profit
                                   && (DayIsOk == true)
                                      //Weekly Profit
                                   && (WeekIsOk == true))
                  conditions

                  Now comes the part that never works correctly.
                  I have it in the following order;

                  Code:
                  // Weekly Profit
                  if ((SystemPerformance.AllTrades.TradesPerformance.Currency.CumProfit - WeeklyAccumulated > Weekly_Profit)
                                  || (SystemPerformance.AllTrades.TradesPerformance.Currency.CumProfit - WeeklyAccumulated < -Weekly_Loss))
                                  if(weeklyprintonetime)
                              {
                                  WeekIsOk = false;
                                  Print ( "Weekly profit/loss hit");
                                      weeklyprintonetim = false;
                              }
                  
                      // Daily limit
                              if ((SystemPerformance.AllTrades.TradesPerformance.Currency.CumProfit - DailyAccumulated > Max_Profit)
                                  || (SystemPerformance.AllTrades.TradesPerformance.Currency.CumProfit - DailyAccumulated < -Max_Loss))
                                  if(printOneTime)
                              {
                                  DayIsOk = false;
                                  Print ( "Daily profit/loss hit");
                                      printOneTime = false;
                              }
                  
                  //Reset Weekly
                              if (Time[0].DayOfWeek == DayOfWeek.Sunday)
                              {
                                  WeekIsOk = true;
                                  WeeklyAccumulated = 0;
                                  weeklyprintonetime = true;
                              }
                  
                              // Reset accumulated profit for the day
                              if (Times[0][0].TimeOfDay < reset_time.TimeOfDay)
                  
                              {
                  
                                  DayIsOk = true;
                                  DailyAccumulated = SystemPerformance.AllTrades.TradesPerformance.Currency.CumProfit;
                                  printOneTime = true;
                              }
                                  }
                  In this state, it will ignore the daily limit and trade out till it hits the weekly. If i flip them around, it will trade to the daily limits and ignore the weekly completely.

                  I thought there would be an easier way for me to Add/subtract the daily total to the prior day and store it as a digit, and calculate in real time, the daily's pnl with the accumulated to know if it's allowed to trade or not. I thought that's what i was trying to do here, but maybe it requires a whole different set of code to achieve.
                  Last edited by adrew99; 08-06-2019, 01:25 PM.

                  Comment


                    #10
                    Hello adrew99,

                    Thank you for the reply.

                    This may be related the following syntax, however it is hard to tell when the script is broken into pieces like this, generally I suggest to copy/paste the script whole or attach it for clarity.

                    Code:
                     //Daily Profit
                    && (DayIsOk == true)
                     //Weekly Profit
                    && (WeekIsOk == true))
                    I cant tell from this snippet if the whole condition should still allow trades, I can see that these variables should require both conditions to be true, if one of them is false it will stop the condition. Because I cant see the overall condition I am unsure if anything else may be wrong there which is allowing it to work.

                    The part you said never works right seems to all be independent conditions, so that all should technically work or be independent of the other conditions. What part of this logic are you noting is not working right, just that your other conditions are still allowing one situation?

                    I look forward to being of further assistance.
                    JesseNinjaTrader Customer Service

                    Comment


                      #11
                      Thanks Jesse for reply.
                      Bellow is an entire test strategy that i run with the same required conditions. You'll see the requirements to take a trade are simple.

                      Code:
                      namespace NinjaTrader.NinjaScript.Strategies
                      {
                          public class CrudeStrategy : Strategy
                          {
                              private SMA SMA1;
                              private bool DayIsOk;
                              private bool WeekIsOk;
                              private double Accumulated;
                              private double DailyAccumulated;
                              private double WeeklyAccumulated;
                              private double Profit = 550;
                              private double Loss = 450;
                              private double WeeklyProfit = 1200;
                              private double WeeklyLoss = 1200;
                              private DateTime reset_time;
                      
                              private bool doOneTime = true;
                              private bool printOneTime = true;
                              private bool weeklyprintonetime = true;
                      
                              private bool shortStopOne = true;
                              private bool longStopOne = true;
                      
                              private bool TargetLongOne = true;
                              private bool TargetShortOne = true;
                      
                              private int barCount = 15;
                              private int target = 21;
                              private int stop = 17;
                              private int mo_avg = 9;
                      
                              protected override void OnStateChange()
                              {
                                  if (State == State.SetDefaults)
                                  {
                                      Description                                    = @"Enter the description for your new custom Strategy here.";
                                      Name                                        = "CrudeStrategy";
                                      Calculate                                    = Calculate.OnEachTick;
                                      EntriesPerDirection                            = 1;
                                      EntryHandling                                = EntryHandling.AllEntries;
                                      IsExitOnSessionCloseStrategy                = true;
                                      ExitOnSessionCloseSeconds                    = 300;
                                      IsFillLimitOnTouch                            = false;
                                      MaximumBarsLookBack                            = MaximumBarsLookBack.TwoHundredFiftySix;
                                      OrderFillResolution                            = OrderFillResolution.Standard;
                                      Slippage                                    = 0;
                                      StartBehavior                                = StartBehavior.WaitUntilFlat;
                                      TimeInForce                                    = TimeInForce.Gtc;
                                      TraceOrders                                    = false;
                                      RealtimeErrorHandling                        = RealtimeErrorHandling.StopCancelClose;
                                      StopTargetHandling                            = StopTargetHandling.PerEntryExecution;
                                      BarsRequiredToTrade                            = 20;
                                      // Disable this property for performance gains in Strategy Analyzer optimizations
                                      // See the Help Guide for additional information
                                      Profit = Max_Profit;
                                      Loss = Max_Loss;
                      
                                      WeeklyProfit = Weekly_Profit;
                                      WeeklyLoss = Weekly_Loss;
                                      // reset time for daily profit_loss
                                      DayIsOk        = true;
                                      WeekIsOk    = true;
                                      Accumulated    = 0;
                                      DailyAccumulated = 0;
                                      WeeklyAccumulated = SystemPerformance.AllTrades.TradesPerformance.Currency.CumProfit;
                      
                                      reset_time = DateTime.Parse("00:05", System.Globalization.CultureInfo.InvariantCulture);
                                  }
                                  else if (State == State.Configure)
                                  {
                                  }
                                  else if (State == State.DataLoaded)
                                  {
                                      SMA1                = SMA(Close, mo_avg);
                                       SetProfitTarget(@"", CalculationMode.Ticks, target);
                                      SetStopLoss("", CalculationMode.Ticks, stop, false);
                                     }
                              }
                              protected override void OnBarUpdate()
                              {
                                  if (BarsInProgress != 0) 
                                      return;
                      
                                  if (CurrentBars[0] < 10)
                                  return;
                      
                                  if ((CrossBelow(GetCurrentAsk(0), Low, 10)) // was 12
                      
                                       && (High[1] <= SMA1[0])
                                       && (High[2] <= SMA1[1])
                                       && (Low[0] < Close[1])
                                       && (Low[0] < Low[2])
                                       && (BarsSinceExitExecution() > 1 || BarsSinceExitExecution()== -1)
                                       &&    ((Times[0][0].TimeOfDay > new TimeSpan(19,30,0))
                                      ||    (Times[0][0].TimeOfDay < new TimeSpan(15,00,0)))
                                      //Daily Profit
                                       && (DayIsOk == true)
                                      //Weekly Profit
                                       && (WeekIsOk == true))
                                  {
                                      EnterShortLimit(Convert.ToInt32(DefaultQuantity), GetCurrentAsk(0), ""); 
                                  } 
                      
                                   // Long Trade Setup Requirements
                                      if ((CrossAbove(GetCurrentBid(0), High, 10))
                      
                                      && (Low[1] >= SMA1[0]) 
                                       && (Low[2] >= SMA1[1])
                                       && (High[0] > Close[1])
                                       && (High[0] > High[2])
                                       && (BarsSinceExitExecution() > 1 || BarsSinceExitExecution()== -1)
                                     &&    ((Times[0][0].TimeOfDay > new TimeSpan(19,30,0))
                                      ||    (Times[0][0].TimeOfDay < new TimeSpan(15,00,0)))
                                          //Daily Profit
                                       && (DayIsOk == true)
                                          //Weekly Profit
                                       && (WeekIsOk == true))
                                  {
                                      EnterLongLimit(Convert.ToInt32(DefaultQuantity), GetCurrentAsk(0), @"");
                                  } 
                      
                                  //Reset Stop
                                      if (Position.MarketPosition == MarketPosition.Flat)
                                  {
                                      SetStopLoss (CalculationMode.Ticks, stop);
                                      doOneTime = true;
                      
                                      longStopOne = true;
                                      shortStopOne = true;
                                       }
                      
                                      // Long breakeven Stop
                                      if (Position.MarketPosition == MarketPosition.Long)
                      
                                      {
                                          if (Close[0] >= (Position.AveragePrice + 25 * TickSize)    && longStopOne)
                                          { 
                                              SetStopLoss("",CalculationMode.Price, Position.AveragePrice + 5 * TickSize, true);
                                              longStopOne = false;
                      
                                              if (doOneTime)
                                              {
                                                  Print ("Long stop +4");
                                                  doOneTime = true;
                                              }
                      
                                          }
                      
                                      }
                      
                                      // Short breakeven Taget Stop
                                      if (Position.MarketPosition == MarketPosition.Short)
                      
                                      {
                                          if (Close[0] <= (Position.AveragePrice - 25 * TickSize) && shortStopOne)
                                          { 
                                              SetStopLoss("",CalculationMode.Price, Position.AveragePrice - 5 * TickSize, true);
                                              shortStopOne = false;
                      
                                              if (doOneTime)
                                              {
                                                  Print ("Short Stop -4");
                                                  doOneTime = true;
                                              }
                                          }
                                          }
                      
                                      // Reset Target
                                      if (Position.MarketPosition == MarketPosition.Flat)
                                  {
                                      SetProfitTarget (CalculationMode.Ticks, target);
                                      doOneTime = true;
                                      TargetLongOne = true;
                                     TargetShortOne = true;
                                  }
                      
                                   else if (Position.MarketPosition == MarketPosition.Long)
                                      {
                                          if (Close[0] <= (Position.AveragePrice - 25 * TickSize)    && TargetLongOne)
                                          { 
                                              SetProfitTarget(CalculationMode.Price, Position.AveragePrice + 10 * TickSize, true);
                                              TargetLongOne = false;
                      
                                              if (doOneTime)
                                              {
                                                  Print ("Long Target moved down +4");
                                                  doOneTime = true;
                                              }
                                          }
                                      }
                                       else if (Position.MarketPosition == MarketPosition.Short)
                      
                                      {
                                          if (Close[0] >= (Position.AveragePrice + 25 * TickSize)    && TargetShortOne)
                                          { 
                                              SetProfitTarget(CalculationMode.Price, Position.AveragePrice - 10 * TickSize, true);
                                              TargetShortOne = false;
                      
                                              if (doOneTime)
                                              {
                                                  Print ("Short Target moved up -4");
                                                  doOneTime = true;
                                              }
                                           }
                                        }
                                       // Weekly Profit
                      if ((SystemPerformance.AllTrades.TradesPerformance.Currency.CumProfit - WeeklyAccumulated > Weekly_Profit) 
                                       || (SystemPerformance.AllTrades.TradesPerformance.Currency.CumProfit - WeeklyAccumulated < -Weekly_Loss))                 if(weeklyprintonetime)             {                 WeekIsOk = false;                 Print ( "Weekly profit/loss hit");                     weeklyprintonetim = false;             }              //Reset Daily
                                  if ((SystemPerformance.AllTrades.TradesPerformance.Currency.CumProfit - DailyAccumulated > Max_Profit)
                                      || (SystemPerformance.AllTrades.TradesPerformance.Currency.CumProfit - DailyAccumulated < -Max_Loss))
                                      if(printOneTime)
                                  {
                                      DayIsOk = false;
                                      Print ( "Daily profit/loss hit");
                                          printOneTime = false;
                                  }
                                  //Reset Weekly
                                  if (Time[0].DayOfWeek == DayOfWeek.Saturday)
                                  {
                                      WeekIsOk = true;
                                      WeeklyAccumulated = 0;
                                      weeklyprintonetime = true;
                                  }
                                  // Reset accumulated profit for the day
                                  if (Times[0][0].TimeOfDay < reset_time.TimeOfDay)
                                  {
                                     DayIsOk = true;
                                      DailyAccumulated = SystemPerformance.AllTrades.TradesPerformance.Currency.CumProfit;
                                      printOneTime = true;
                                  }
                                      }
                      Thank you

                      Comment


                        #12
                        see the attached.

                        this is a test strategy that i have these conditions in to makes sure they work before putting them in the real thing
                        Attached Files

                        Comment


                          #13
                          Hello adrew99,

                          Thank you for providing the script that helps.

                          One problem is that you are using State.SetDefaults to set the value of the weekly profit, this should be moved to OnBarUpdate:
                          Code:
                          WeeklyAccumulated = SystemPerformance.AllTrades.TradesPerformance.Currency.CumProfit;
                          You could initialize this property in State.SetDefaults with
                          Code:
                           WeeklyAccumulated = 0;
                          Then later when setting your daily, you could accumulate the weekly:

                          Code:
                          DailyAccumulated = SystemPerformance.AllTrades.TradesPerformance.Currency.CumProfit;
                          WeeklyAccumulated += DailyAccumulated;
                          It looks like you have a reset to 0 for the weekly already so that part should be ok.

                          You may want to add to the condition to reset to make it happen once per session as well:

                          Code:
                          if (Time[0].DayOfWeek == DayOfWeek.Monday && Bars.IsFirstBarOfSession)
                          The daily would be the same case if you are using OnEachTick calculation, the time could be reported more than once in that case which would keep resetting the condition, you may also need to add more logic to control this in realtime.



                          I look forward to being of further assistance.

                          JesseNinjaTrader Customer Service

                          Comment


                            #14
                            Hello again, So I'm back at this, trying to resolve my issues above. I think I got most of the issues sorted out, however I can't seem to get the script to reset the Weeklyaccumulated to Zero (0) when I want it to. I have an "if" statement towards the bottom under "reset Weekly" that states,

                            (Time[0].DayOfWeek == DayOfWeek.Saturday && Bars.IsFirstBarOfSession)
                            { WeeklyAccumulated = 0; }

                            However, it never resets. I've put a "print" statement there as well, to just print that "it's Sunday and this is the first bar of the session" and that works. So this indicates to me, that I have the timing/date setup correctly, but I just can't get the WeeklyAccumulated to Zero out for the start of the week. Can you please provide some more assistance with this one. Thanks, Andrew
                            Last edited by adrew99; 02-26-2020, 04:15 PM.

                            Comment


                              #15
                              Hello adrew99,

                              From the given details I couldn't say what may be happening, do you have a better sample of what you modified/added? Using Prints will be how to figure this out however without seeing more of the code I couldn't really provide any guidance on what else to try.

                              If the value never resets that indicates to me that some logic in between the reset and your print is setting the value or the condition to reset it is not actually working as you are expecting. If you can provide a new sample that shows the print/reset we could continue from there.


                              I look forward to being of further assistance.
                              JesseNinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by mmenigma, Today, 02:22 PM
                              1 response
                              3 views
                              0 likes
                              Last Post NinjaTrader_Jesse  
                              Started by frankthearm, Today, 09:08 AM
                              9 responses
                              35 views
                              0 likes
                              Last Post NinjaTrader_Clayton  
                              Started by NRITV, Today, 01:15 PM
                              2 responses
                              9 views
                              0 likes
                              Last Post NRITV
                              by NRITV
                               
                              Started by maybeimnotrader, Yesterday, 05:46 PM
                              5 responses
                              26 views
                              0 likes
                              Last Post NinjaTrader_ChelseaB  
                              Started by quantismo, Yesterday, 05:13 PM
                              2 responses
                              21 views
                              0 likes
                              Last Post quantismo  
                              Working...
                              X