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

Help with Strategy Daily Profit Target

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

    Help with Strategy Daily Profit Target

    I have a strategy I'm trying to use. I did not create this strategy. The Daily Profit function is not working and would like help to get it working.

    For the daily profit target it states
    "TRADING TIMES/TARGET
    You may optionally enter a Start/Stop time to allow trading along with a price target to end trading for the session early.(Ninjas Session must be set to Daily sessions to work right)"

    I'd like to be able to have the Daily Profit Target work on a Tick/Renko chart.

    Here are the sections of code pertaining to the daily target

    #region Variables

    #region TradeTime Variables
    private int startTime1 = 0; //0930; // Time to start trading
    private int stopTime1 = 0; //1600; // Time to stop trading if target not reached (1600 = 04:00PM)
    private int startTime2 = 0; //0930; // Time to start trading
    private int stopTime2 = 0; //1600; // Time to stop trading if target not reached (1600 = 04:00PM)
    private double profitTarget = 0; // Stop trading for the day if profitTarget reached
    private double priorTradesCumProfit=0; private double profitThisSession=0;
    #endregion



    #region Initialize
    protected override void Initialize()

    protected override void OnBarUpdate()
    {
    #region PreProcess //Only allow Trading if TradeTime/ProfitTarget/

    // TRADING TIME/TARGET CHECK
    //If user has selected a startTime only allow trading if Time >StartTime && Time < stopTime && Profit<profitTarget
    if((tradingAllowed())&&((startTime1>0)||(startTime 2>0)) )
    { if (myPosition(0)==cLong) ExitLong(); if (myPosition(0)==cShort) ExitShort();
    if ((trace)&&((startTime1>0)||(startTime1>0))) Print("Trade Time/Target Violation: "+Time[0].ToString("G")+" must be >"+(startTime1).ToString("##:##")+"and <"+(stopTime1).ToString("##:##")+" Profit is "+profitThisSession.ToString("C")+" Target is $"+profitTarget);
    DrawDiamond(CurrentBar.ToString(), true,0,Low[0],Color.Yellow);
    return;
    }
    if ((trace)&&((startTime1>0)||(startTime1>0)) ) Print("Trade Time/Target OK:"+Time[0].ToString("G")+" Session Profit:"+profitThisSession.ToString("C"));

    #endregion




    #region UserDefinedMethods
    //
    private bool tradingAllowed() // Called if user selected a trade time limit and/or profit target for the session.
    { if (Bars.FirstBarOfSession) //If first bar of session, move previous session total to cumulative total bucket
    { if(trace) Print("FirstBarOfSession");
    priorTradesCumProfit = Performance.AllTrades.TradesPerformance.Currency.C umProfit;
    }
    profitThisSession=Performance.AllTrades.TradesPerf ormance.Currency.CumProfit - priorTradesCumProfit; //store session closed trade profit/losses
    if ((Position.GetProfitLoss(Close[0],PerformanceUnit.Currency)+profitThisSession)>prof itTarget) //if open trade profits plus closed session trade profits reach target add them together
    { profitThisSession=profitThisSession+Position.GetPr ofitLoss(Close[0],PerformanceUnit.Currency); //this will trigger trade violation and close trading for session
    }
    return ( (startTime1==0&&startTime2==0)||((ToTime(Time[0])>=startTime1*100&&ToTime(Time[0])<stopTime1*100)||(ToTime(Time[0])>=startTime2*100&&ToTime(Time[0])<stopTime2*100)&&(profitTarget==0||profitThisSess ion<=profitTarget)) );
    }//ENDprofitThisSession()




    Any help with this would be appreciated! Here is the full Script Automated Ninjaworkshop1.3 Strategy.zip

    #2
    Hello Displacer,

    Thank you for the post.

    I wanted to check, what specifically are you seeing that is not working when using this with Tick/Renko charts? is it that the DrawDiamond is not happening or could you further explain what specifically is not happening?

    Can you provide an example of the test you are doing so that I can run the strategy in the same situation? That would be helpful in explaining the question.

    I also am not certain what relation the following comment has to the other syntax provided, have you found this comment to be related in some way?

    For the daily profit target it states
    "TRADING TIMES/TARGET
    You may optionally enter a Start/Stop time to allow trading along with a price target to end trading for the session early.(Ninjas Session must be set to Daily sessions to work right)"


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

    Comment


      #3
      Hello,
      What is not working is the Profit Target for the session. Lets say I want to trade from 0930 to 1600 with a profit for the session of $100. The strategy will trade from 0930 to 1600 properly but does not stop after the Profit Target for the session has been reached. It continues to trade until the stop time of 1600. As I said, I did not create this strategy and the original creator cannot be found.

      Also, I am not a programmer and I only understand the basics of the code which is why I am seeking help with it. The Sections of code that I listed above in their perspective Regions is what I believe to be related to the session Profit Target.

      The comment of
      "TRADING TIMES/TARGET
      You may optionally enter a Start/Stop time to allow trading along with a price target to end trading for the session early.(Ninjas Session must be set to Daily sessions to work right)"
      was in the description of the strategy.

      The Settings I am using:
      Chart: NQ
      Renko- Brick Size = 10
      With Heiken Ashi Indicator

      Strategy:
      AutoTrendH

      Enable Control = Entrys
      Alerts = True
      EnterBreaks = True
      ShowHistory = True
      Strength = 5
      EMA Crossings Control - Disabled
      MACD Crossover Control - Disabled
      RSI Control - Disabled
      Scalper Control - Disabled
      Slope Control - Disabled
      TrendChannel Control - Disabled
      Entry Limits:

      Enable LongTrend Control = Disabled
      Entry Limit = Both
      Previous Bar Limit = False
      ReEntry Bars Delay = False
      ReEntry Prevention = True
      Reverse Triggers = False
      Manage Trade:
      ATM Handoff Template - Blank
      Max Entries = 1
      StopEven = 0
      StopLoss = 0
      StopProfit = 0
      StopShock = 0
      Stop Markers = True
      Trace = False
      TrailStop Method = ATR
      TrailATR Mult. = 3.5
      Trading Time Control
      1)Start Time = 0930
      1)Stop Time = 1600
      2)Start Time = 0
      2)Stop Time = 0
      Profit Target = 100 <(This should stop the strategy until the next session once target is achieved but is not working)

      Account -Replay 101
      Entry Handling = Unique Entries
      Exit on Close = True- 30 Sec



      Thanks for your help!

      Comment


        #4
        Hello Displacer,

        Thank you for the reply.

        Yes, in this case, this would likely require to debug the strategy to find out what is going on in that situation. I see that the script has some prints in it already, during the time where this fails can you try opening the Tools -> Output Window to see if there are prints showing up? Also just to confirm, are you seeing the yellow diamond? This would just help to know where in the logic it is failing, if you are not seeing the yellow diamond it is very likely the part of the code you highlighted.

        If the strategy continues to trade beyond the condition that was set, it is very likely one of the variables used in the condition is a value which the strategy did not expect leaving the condition false. The part of the logic you had highlighted contains quite a few variables which would need to be reviewed to see why it is failing.


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

        Comment


          #5
          Yes, I can see the yellow diamonds under the bars during the times that trading is not allowed ie <0930 and >1600.

          Ok, I will run the strat. again with the output window and copy the results for you.

          Thank for the help!

          Comment


            #6
            Ok, so I ran the strategy on market replay for the first few mins of market open and after a few trades the realized Pnl was $140 but the strategy continued trading as you'll see in the last part of the log. NinjaWorkShop1_3__Output log.txt

            Comment


              #7
              Hello Displacer,

              Thank you for the reply.

              I took a look at the output in contrast to the script but I cannot see anything that would be a simple fix here. The script has quite a few logical paths which it can take and seems to be reaching the trading logic although you are specifying a profit target. I am unsure if this is simply the combination of settings being used or a greater problem with the logic, this would require looking into the code more closely. If this is something you are interested in doing yourself I can provide further guidance on debugging and ways to approach that, otherwise this would likely be an item you would need to reach out to a NinjaScript developer for further assistance.

              I look forward to being of further assistance.

              JesseNinjaTrader Customer Service

              Comment


                #8
                Well that's a bummer that it's not an easy fix but I am very much willing to learn what I need to do to debug and fix it if you're willing to help me with that.

                Comment


                  #9
                  Ok, so far I have followed the NT7 help guide to use Visual Studio 2017 to attach NinjaTrader.exe and have loaded up the Ninjaworkshop.cs file but am unsure of what to do next.

                  Thanks for your help Jesse!

                  Comment


                    #10
                    Hello Displacer,

                    Thank you for the reply.

                    In this situation, if you know how to use visual studio already you can utilize it to attach to NinjaTrader and use breakpoints to test the script but this would not be my first suggestion at debugging the script. I would likely suggest to first use some additional prints to gain better insight into the problem. If you would like to use visual studio for debugging in NT7 there are additional steps which would be needed that are not documented, please see the video in the following link: http://www.screencast.com/t/eH7y5cedlzh

                    We have a short debugging guide in the following link which explains prints more: https://ninjatrader.com/support/help...script_cod.htm

                    Because existing logic is not working as you expect in a certain use case, you can run the script in that same use case and output the values of the conditions it uses to see what specifically is failing. The prints the script has now are not apparent to me what is specifically failing and may not be completely helpful in debugging the script, you may want to first go through and comment out the existing prints so you can see only your added prints:
                    Code:
                    //Print(""); // two slashes at the beginning comment out a line of code
                    If you do this change you would also need to right click and compile the script.

                    The code you had highlighted originally would likely be the logical place to start as there is a method named tradingAllowed(), this would seem to me like a good location to test what value is being seen during the test. You could do this by using a print, here is one example:

                    Code:
                    // TRADING TIME/TARGET CHECK    
                    //If user has selected a startTime only allow trading if Time >StartTime && Time < stopTime && Profit<profitTarget
                    
                    [B]Print("tradingAllowed: " + !tradingAllowed() + " (startTime1>0): " + (startTime1>0) + " (startTime2>0): " + (startTime2>0));[/B]
                    
                    if((!tradingAllowed())&&((startTime1>0)||(startTime2>0)) )
                    If you do this change you would also need to right click and compile the script.


                    You can print most objects being used in the script similar to the print shown above, based on the output of this print you could judge if the condition should have been true or false based on the time variables and true/false value of the trading tradingAllowed method. This would help decide if the problem is with one of these items, or further into the logic.


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

                    Comment


                      #11
                      Awesome, thanks for the help!
                      I actually think I figured out a simple fix.

                      I added the code &&(profitThisSession<=profitTarget) to the entries area and it works fine.
                      Code:
                      //ENTRYS        
                              //LongEntry
                              if ((longEntryTrigger) && (!longExitTrigger)[COLOR=#FF0000][B]&&(profitThisSession<=profitTarget)[/B])[/COLOR]
                      {    if (myPosition(0)!=cLong) { posCtr=0; lastEntry=0; }     //If this is first long entry, reset counters
                                  if ( (posCtr<maxEntries)&&(Close[0]>lastEntry))            //Open another Long position if positions less then max entries and current close is higher then last open
                                  {    if ( (stopLoss>0)||(stopEven>0)||(TrailStop!=TrailStops.Disabled) )        {    setMultiStop("L","Ticks",maxEntries,0);    }
                                      lastEntry=Close[0];        posCtr=posCtr+1;    previousMaxMove=0;    delayCounter=0; lastDir= cLong;
                                      if(_ATMTemplate=="")    EnterLong("L"+posCtr);    else    if (myPosition(0)!=cLong){atmCommand("BuyLong");}
                                      return;    
                              }    }
                      Then I created the following new code to try to limit the daily loss
                      Code:
                      #region TradeTime Variables
                      [B][COLOR=#FF0000]           private double lossThisSession = 0;[/COLOR][/B]
                      
                      #region UserDefinedMethods
                          private bool tradingAllowed() // Called if user selected a trade time limit and/or profit target for the session.
                                 { if (Bars.FirstBarOfSession) //If first bar of session, move previous session total to cumulative total bucket
                                 { if(trace) Print("FirstBarOfSession");
                                 priorTradesCumProfit = Performance.AllTrades.TradesPerformance.Currency.CumProfit;
                                 }
                                 profitThisSession=Performance.AllTrades.TradesPerf ormance.Currency.CumProfit - priorTradesCumProfit; //store session closed trade profit/losses
                      [B][COLOR=#FF0000]           lossThisSession=Performance.AllTrades.TradesPerfor mance.Currency.CumProfit - priorTradesCumProfit;[/COLOR][/B]
                      
                      #region Properties
                           #region Tradeing Times
                      [COLOR=#FF0000][B]          [Description("Stops trading only if LossLimit reached (Enter Dollar Amount)")]
                                [GridCategory("Trading Time Control")]
                                public double LossLimit { get { return lossLimit; } set { lossLimit = value; } }[/B][/COLOR]
                      And then tried the to apply it the same way
                      Code:
                      //ENTRYS        
                              //LongEntry
                              if ((longEntryTrigger) &&(!longExitTrigger)&&(profitThisSession<=profitTarget)[B][COLOR=#FF0000] &&(lossThisSession<= - profitTarget))[/COLOR][/B]
                      {    if (myPosition(0)!=cLong) { posCtr=0; lastEntry=0; }     //If this is first long entry, reset counters
                                  if ( (posCtr<maxEntries)&&(Close[0]>lastEntry))            //Open another Long position if positions less then max entries and current close is higher then last open
                                  {    if ( (stopLoss>0)||(stopEven>0)||(TrailStop!=TrailStops.Disabled) )        {    setMultiStop("L","Ticks",maxEntries,0);    }
                                      lastEntry=Close[0];        posCtr=posCtr+1;    previousMaxMove=0;    delayCounter=0; lastDir= cLong;
                                      if(_ATMTemplate=="")    EnterLong("L"+posCtr);    else    if (myPosition(0)!=cLong){atmCommand("BuyLong");}
                                      return;    
                              }    }
                      And then it doesn't trade at all!

                      So, then I tried using
                      #region TradeTime Variables
                      private int lossLimit =0;
                      also tried
                      private double lossLimit=0;

                      And entered it like so
                      Code:
                      //ENTRYS        
                              //LongEntry
                              if ((longEntryTrigger) && (!longExitTrigger)&&(profitThisSession<=profitTarget)[COLOR=#FF0000][B]&&(lossThisSession<= -lossLimit))[/B][/COLOR]
                      {    if (myPosition(0)!=cLong) { posCtr=0; lastEntry=0; }     //If this is first long entry, reset counters
                                  if ( (posCtr<maxEntries)&&(Close[0]>lastEntry))            //Open another Long position if positions less then max entries and current close is higher then last open
                                  {    if ( (stopLoss>0)||(stopEven>0)||(TrailStop!=TrailStops.Disabled) )        {    setMultiStop("L","Ticks",maxEntries,0);    }
                                      lastEntry=Close[0];        posCtr=posCtr+1;    previousMaxMove=0;    delayCounter=0; lastDir= cLong;
                                      if(_ATMTemplate=="")    EnterLong("L"+posCtr);    else    if (myPosition(0)!=cLong){atmCommand("BuyLong");}
                                      return;    
                              }    }
                      And yet again it doesn't trade at all. I'm not sure what else to try to get it working with a LossLimit as well.

                      Comment

                      Latest Posts

                      Collapse

                      Topics Statistics Last Post
                      Started by DJ888, Today, 10:57 PM
                      0 responses
                      6 views
                      0 likes
                      Last Post DJ888
                      by DJ888
                       
                      Started by MacDad, 02-25-2024, 11:48 PM
                      7 responses
                      158 views
                      0 likes
                      Last Post loganjarosz123  
                      Started by Belfortbucks, Today, 09:29 PM
                      0 responses
                      7 views
                      0 likes
                      Last Post Belfortbucks  
                      Started by zstheorist, Today, 07:52 PM
                      0 responses
                      7 views
                      0 likes
                      Last Post zstheorist  
                      Started by pmachiraju, 11-01-2023, 04:46 AM
                      8 responses
                      151 views
                      0 likes
                      Last Post rehmans
                      by rehmans
                       
                      Working...
                      X