Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Profit Target Quantity issue

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

    Profit Target Quantity issue

    Hi Ninjatrader community,

    I'm having a problem with Profit target quantity. I'm submitting two entries in my strategy and for the second entry of these two I'm trying to set a profit target.
    Profit target is set and executed according to the configuration but it is being executed for both entries (2 quantity instead of 1), instead for the first entry only. In backtesting the strategy works fine but in market replay or on live trading the problem occurs. You can see the issue in the picture (the second order is executed with market replay and first one is how it should work which is also shown in backtest).

    Below is my code:
    Code:
    //This namespace holds Strategies in this folder and is required. Do not change it.
    namespace NinjaTrader.NinjaScript.Strategies
    {
        public class Strategyname : Strategy
        {
    
            private HMA HMA1;
            private bool TradeAika;
            private bool TradeAika2;
            private bool OkToTrade;
            private bool triggerStopLoss = false;
    
            private const string Longentry1 = "Longentry1";
            private const string Longentry2 = "Longentry2";
            private const string Shortentry1 = "Shortentry1";
            private const string Shortentry2 = "Shortentry2";
    
            protected override void OnStateChange()
            {
                if (State == State.SetDefaults)
                {
                    Description                                    = @"Enter the description for your new custom Strategy here.";
                    Name                                        = "Strategyname";
                    Calculate                                    = Calculate.OnBarClose;
                    EntryHandling                                = EntryHandling.UniqueEntries;
                    IsExitOnSessionCloseStrategy                = true;
                    ExitOnSessionCloseSeconds                    = 30;
                    IsFillLimitOnTouch                            = false;
                    MaximumBarsLookBack                            = MaximumBarsLookBack.TwoHundredFiftySix;
                    OrderFillResolution                            = OrderFillResolution.Standard;
                    Slippage                                    = 0;
                    StartBehavior                                = StartBehavior.WaitUntilFlat;
                    TimeInForce                                    = TimeInForce.Gtc;
                    TraceOrders                                    = true;
                    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
                    IsInstantiatedOnEachOptimizationIteration    = true;
                    AloitusAika1 = 163000;
                    LopetusAika1 = 180000;
                    AloitusAika2 = 210000;
                    LopetusAika2 = 230000;
                    // Entry
                    EntryQuantity = 2;
                    PTargetValue = 100;
                    HMAperiod = 50;
                    Monday = true;
                    Tuesday = true;
                    Wednesday = true;
                    Thursday = true;
                    Friday = true;
                    EntriesPerDirection = 2;
                }
                else if (State == State.Configure)
                {
                }
                else if (State == State.DataLoaded)
                {                
                }
            }
    
            protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time) {
                if (execution.IsEntryStrategy) {
                     if (execution.Name == Longentry1) {
                        SetProfitTarget(execution.Name, CalculationMode.Currency, PTargetValue);
                      }
                      else if (execution.Name == Shortentry1) {
                        SetProfitTarget(execution.Name, CalculationMode.Currency, PTargetValue);
                      }
                }    
            }
    
            private void ResetProfitStop()
            {
                SetProfitTarget(Longentry1, CalculationMode.Ticks, 2000, true);
                SetProfitTarget(Shortentry1, CalculationMode.Ticks, 2000, true);
            }
    
    
            protected override void OnPositionUpdate(Cbi.Position position, double averagePrice,
                                                      int quantity, Cbi.MarketPosition marketPosition)
            {
              if (marketPosition != MarketPosition.Flat) {
                  if (quantity == EntryQuantity && !triggerStopLoss) {
                      triggerStopLoss = true;
                  } else if (quantity == (EntryQuantity / 2) && triggerStopLoss) {
                      if (marketPosition == MarketPosition.Long && StopLossRest) {
                        ExitLongStopMarket((Convert.ToInt32(EntryQuantity / 2)), position.AveragePrice, "Break even Long", Longentry2);
                      }
                      else if (marketPosition == MarketPosition.Short && StopLossRest) {
                          ExitShortStopMarket((Convert.ToInt32(EntryQuantity / 2)), position.AveragePrice, "Break even Short", Shortentry2);
                      }
                  }
              }
              else
              {
                triggerStopLoss = false;
              }
            }
    
            protected override void OnBarUpdate()
            {
                TradeAika = false;
                TradeAika2 = false;
                OkToTrade = false;
    
                if (
                     // SundayCheck
                    ((Sunday == true)
                     && (Times[0][0].DayOfWeek == DayOfWeek.Sunday))
                     // MondayCheck
                     || ((Monday == true)
                     && (Times[0][0].DayOfWeek == DayOfWeek.Monday))
                     // TuesdayCheck
                     || ((Tuesday == true)
                     && (Times[0][0].DayOfWeek == DayOfWeek.Tuesday))
                     // WednesdayCheck
                     || ((Wednesday == true)
                     && (Times[0][0].DayOfWeek == DayOfWeek.Wednesday))
                     // ThursdayCheck
                     || ((Thursday == true)
                     && (Times[0][0].DayOfWeek == DayOfWeek.Thursday))
                     // FridayCheck
                     || ((Friday == true)
                     && (Times[0][0].DayOfWeek == DayOfWeek.Friday))
                     || ((Saturday == true)
                     && (Times[0][0].DayOfWeek == DayOfWeek.Saturday)))
                {
                    OkToTrade = true;
                }
    
    
                if (BarsInProgress != 0)
                    return;
    
                if (CurrentBars[0] < 1)
                    return;
    
                if (Position.MarketPosition == MarketPosition.Flat)
                {
                    ResetProfitStop();
                }
    
                 if (Position.MarketPosition != MarketPosition.Flat && StopLossRest) {
                    if (Position.Quantity == (EntryQuantity / 2) && triggerStopLoss) {
                          if (Position.MarketPosition == MarketPosition.Long) {
                            ExitLongStopMarket((Convert.ToInt32(EntryQuantity / 2)), Position.AveragePrice, "Break even Long", Longentry2);
                          }
                          else {
                              ExitShortStopMarket((Convert.ToInt32(EntryQuantity / 2)), Position.AveragePrice, "Break even Short", Shortentry2);
                          }
                      }
                  }
    
                  // If the range is on the same day, both expressions must be true
                  if (AloitusAika1 < LopetusAika1)
                  {
                    TradeAika = (ToTime(Time[0]) >= AloitusAika1) && (ToTime(Time[0]) <= LopetusAika1);
                  }
                  else
                  {
                      TradeAika = (ToTime(Time[0]) > AloitusAika1) || (ToTime(Time[0]) < LopetusAika1);
                  }
                  // If the range is on the same day, both expressions must be true
                  if (AloitusAika2 < LopetusAika2)
                  {
                    TradeAika2 = (ToTime(Time[0]) >= AloitusAika2) && (ToTime(Time[0]) <= LopetusAika2);
                  }
                  else
                  {
                      TradeAika2= (ToTime(Time[0]) > AloitusAika2) || (ToTime(Time[0]) < LopetusAika2);
                  }
    
    
                if ((TradeAika || TradeAika2) && OkToTrade)
                {
                     // Enter Long
                    if (Logic to enter long)
                    {
                        EnterLong((Convert.ToInt32(EntryQuantity / 2)), Longentry1);
                        EnterLong((Convert.ToInt32(EntryQuantity / 2)), Longentry2);
                    }
    
                     // Enter short
                    if (Logic to enter short))
                    {
                        EnterShort((Convert.ToInt32(EntryQuantity / 2)), Shortentry1);
                        EnterShort((Convert.ToInt32(EntryQuantity / 2)), Shortentry2);
                    }
                }
                // Exit Long
                if (Logic for exit long)
                {
                    ExitLong(Convert.ToInt32(EntryQuantity), @"ExitLong", "");
                }
    
                 // Exit Short
                if (Logic for exit short)
                {
                    ExitShort(Convert.ToInt32(EntryQuantity), @"ExitShort", "");
                }
            }
    
                    #region Properties
    
            [NinjaScriptProperty]
            [Range(2, int.MaxValue)]
            [Display(Name="EntryQuantity", Description="Kuinka entry positiota tehdään, HUOM! Vain parillinen luku", Order=1, GroupName="Entry Parameters")]
            public int EntryQuantity
            { get; set; }
    
            [NinjaScriptProperty]
            [Range(1, int.MaxValue)]
            [Display(Name="Ensimmäinen Aloitus aika", Description="Koska tradaus alkaa XXYYZZ XX=tunnit, YY=minuutit, ZZ=sekunnit", Order=1, GroupName="Tradeus aika-arvot")]
            public int AloitusAika1
            { get; set; }
    
            [NinjaScriptProperty]
            [Range(1, int.MaxValue)]
            [Display(Name="Ensimmäinen Lopetus aika", Description="Koska tradaus loppuu XXYYZZ XX=tunnit, YY=minuutit, ZZ=sekunnit", Order=2, GroupName="Tradeus aika-arvot")]
            public int LopetusAika1
            { get; set; }
    
            [NinjaScriptProperty]
            [Range(1, int.MaxValue)]
            [Display(Name="Toinen Aloitus aika", Description="Koska tradaus alkaa XXYYZZ XX=tunnit, YY=minuutit, ZZ=sekunnit", Order=3, GroupName="Tradeus aika-arvot")]
            public int AloitusAika2
            { get; set; }
    
            [NinjaScriptProperty]
            [Range(1, int.MaxValue)]
            [Display(Name="Toinen Lopetus aika", Description="Koska tradaus loppuu XXYYZZ XX=tunnit, YY=minuutit, ZZ=sekunnit", Order=4, GroupName="Tradeus aika-arvot")]
            public int LopetusAika2
            { get; set; }
    
            [NinjaScriptProperty]
            [Display(Name="Maanantai?", Description="True = Tradee maanantaisin", Order=1, GroupName="Tradeus viikonpäivät")]
            public bool Monday
            { get; set; }
    
            [NinjaScriptProperty]
            [Display(Name="Tiistai?", Description="True = Tradee tiistaisin", Order=2, GroupName="Tradeus viikonpäivät")]
            public bool Tuesday
            { get; set; }
    
            [NinjaScriptProperty]
            [Display(Name="Keskiviikko?", Description="True = Tradee keskiviikkoisin", Order=3, GroupName="Tradeus viikonpäivät")]
            public bool Wednesday
            { get; set; }
    
            [NinjaScriptProperty]
            [Display(Name="Torstai?", Description="True = Tradee torstaisin", Order=4, GroupName="Tradeus viikonpäivät")]
            public bool Thursday
            { get; set; }
    
            [NinjaScriptProperty]
            [Display(Name="Perjantai?", Description="True = Tradee perjantaisin", Order=5, GroupName="Tradeus viikonpäivät")]
            public bool Friday
            { get; set; }
    
            [NinjaScriptProperty]
            [Display(Name="Lauantai?", Description="True = Tradee lauantaisin", Order=6, GroupName="Tradeus viikonpäivät")]
            public bool Saturday
            { get; set; }
    
            [NinjaScriptProperty]
            [Display(Name="Sunnuntai?", Description="True = Tradee Sunnuntaisin", Order=7, GroupName="Tradeus viikonpäivät")]
            public bool Sunday
            { get; set; }
    
            [NinjaScriptProperty]
            [Range(0, double.MaxValue)]
            [Display(Name="Profit Target", Description="Määritä profit targetin määrä", Order=4, GroupName="ProfitTarget Parameters")]
            public double PTargetValue
            { get; set; }
    
            [NinjaScriptProperty]
            [Display(Name="Stop loss loput sopimukset", Description="True = Asettaa stop loss arvon osto hintaan lopuille sopimuksille", Order=7, GroupName="Stoploss Parameters")]
            public bool StopLossRest
            { get; set; }        
    
            #endregion
        }
    }
    ​

    What could be the issue here? Any advises are appreciated, thank you.
    Attached Files

    #2
    Hello jmarkkula,

    Thank you for your post.

    I see that you are calling SetProfitTarget() inside of OnExecutionUpdate(), however as noted in the help guide, "Since they are submitted upon receiving an execution, the Set method should be called prior to submitting the associated entry order to ensure an initial level is set." I recommend moving your logic for the SetProfitTarget() methods to OnStateChange() when State == State.Configure if you plan to use the same profit offset, or if you plan to reset the profit target to a different offset later on you could put them into OnBarUpdate() before your entries are submitted and remember to reset the value whenever your position is flat. Using execution.Name to populate the fromEntrySignal string would not work if calling the set methods from OnStateChange() or OnBarUpdate(), so you would need to input the string as Longentry1 or Shortentry1 as needed.

    ​We have a reference sample strategy that demonstrates how to set a stop loss and profit target in State.Configure. It moves the Stop Loss to breakeven after a certain amount of profit, then when the position is flat it resets the stop loss to the original value from State.Configure. That sample may be found here:



    Here is the help guide page for SetProfitTarget() for additional information, including notes and tips for using Set() methods:


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

    Comment

    Latest Posts

    Collapse

    Topics Statistics Last Post
    Started by Barry Milan, Yesterday, 10:35 PM
    5 responses
    16 views
    0 likes
    Last Post NinjaTrader_Manfred  
    Started by DanielSanMartin, Yesterday, 02:37 PM
    2 responses
    13 views
    0 likes
    Last Post DanielSanMartin  
    Started by DJ888, 04-16-2024, 06:09 PM
    4 responses
    13 views
    0 likes
    Last Post DJ888
    by DJ888
     
    Started by terofs, Today, 04:18 PM
    0 responses
    12 views
    0 likes
    Last Post terofs
    by terofs
     
    Started by nandhumca, Today, 03:41 PM
    0 responses
    8 views
    0 likes
    Last Post nandhumca  
    Working...
    X