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

Breakeven based on High and Close at entry

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

    Breakeven based on High and Close at entry

    Hi guys,

    I am trying to create a Breakeven order when the Initial Risk is earned. However, the Initial StopLoss varies from entry to entry, because the entry is a Bearish Engulfing patern:

    protected override void OnBarUpdate()
    {
    if (CurrentBar < 1)
    return;

    if (Close[1] > Open[1] && Close[0] < Open[0] && Open[0] >= Close[1] && Close[0] <= Open [1])
    {
    EnterShort(DefaultQuantity, "BearishEngulfing");

    double difference = High[0] - Close[0];

    SetStopLoss(CalculationMode.Price, High[0]);
    SetProfitTarget(CalculationMode.Ticks, TickSize*(8*difference));
    }
    if (Low[0] < Position.AveragePrice + (difference*4*TickSize))
    {
    SetStopLoss(CalculationMode.Price, Position.AveragePrice);
    }

    }

    I tried to find a way to store the value of the variable "difference" somehow, but did not find a way to do so. As seen in the bold part the if statement requires the difference value, but the value is not reachable from the if statement above.

    Do you have an idea how to make it reachable or to store the value of difference so the second if statement can be executed?

    Thanks in advance!
    Last edited by slimwin; 10-15-2017, 01:21 PM.

    #2
    Hello slimwin,

    Likely you are having an issue with scope.

    Declare the double you are attempting to store the value with in the scope of the class and not within the scope of OnBarUpdate.

    (Meaning declare the variable in the variables region which is in the scope of the class)

    Below is a publicly available link to a 3rd party educational site on scope.



    Also, always set the stop loss and profit target before placing an order, not after. (As they will continue using older values)
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Thanks Chelsea for the fast response!

      I have done some research on how to get the value from my entry point into the condition of my Breakeven Stoploss.

      As you mentioned a variable in the class scope may be a good idea, but since OnBarUpdate changes the values of High[0] and Close[0] with each bar created, subsequently the BE condition would use the values of the latest created bar. Am I getting it right??

      However, I thought about creating a method, which counts the bars passed since the entry, but stumbled across BarSinceEntryExecution(). Based on that I modified the code a bit:

      Code:
      else if (State == State.Configure)
                  {
                          SetStopLoss(CalculationMode.Ticks, 10000);
                          SetProfitTarget(CalculationMode.Ticks, 10000);
                  }
              }
              protected override void OnBarUpdate()
              {
                  if (CurrentBar < BarsRequiredToTrade)
                      return;
                  
                  // Resets the stop loss to the original value when all positions are closed
                  if (Position.MarketPosition == MarketPosition.Flat)
                  {
                      SetStopLoss(CalculationMode.Price, High[0]);
      SetProfitTarget(CalculationMode.Price, Close[0] - ((High[0] - Close[0])*2));
                  }
                  
                  // If a long position is open, allow for stop loss modification to breakeven
                  else if (Position.MarketPosition == MarketPosition.Short)
                  {
                      // Once the price is greater than entry price+InitialSL, set stop loss to breakeven
                      if (Low[0] < Close[BarsSinceEntryExecution("BearEng")] + (High[BarsSinceEntryExecution("BearEng")] - Close[BarsSinceEntryExecution("BearEng")]))
      {
      SetStopLoss(CalculationMode.Price,Close[BarsSinceEntryExecution("BearEng")]);
      }
                  }
                  
                  // Entry Condition: Bearish Engulfing
                  if (Close[1] > Open[1] && Close[0] < Open[0] && Open[0] >= Close[1] && Close[0] <= Open[1])
                  {
                      EnterShort(DefaultQuantity, "BearEng");
                  
                      Draw.ArrowDown(this,"BEmarker" + CurrentBar, false, 0, High [0] + TickSize, Brushes.Orange);
                  }
              }
      Is the usage of BarsSinceEntryExecution() viable this way?
      And how are Stop Losses handled in a backtest, when the logic is calculated on each bar? Since my StopLosses seem to be executed arbitrarly...(See attachment)

      Thank You!
      Attached Files
      Last edited by slimwin; 10-20-2017, 05:25 AM.

      Comment


        #4
        Hello slimwin,

        Thanks for your additional questions.

        As you mentioned a variable in the class scope may be a good idea, but since OnBarUpdate changes the values of High[0] and Close[0] with each bar created, subsequently the BE condition would use the values of the latest created bar. Am I getting it right??
        OnBarUpdate() will iterate CurrentBar and the bars ago with each bar created. When Calculate is set to OnEachTick, Close[0] will update with the latest value after each tick until the bar is closed, in which that bar will become Close[1]. The tick received after the the time of the bar close then starts the new bar with Close[0]. A barsAgo index of 0 would be the current bar, and an index of one would be the previous bar. I've attached an image that describes OnBarUpdate() calculates when set to OnBarClose vs. OnEachTick.

        Your breakeven condition could follow any logic you deem reasonable to move your stop loss. You could use the price level with a barsAgo for a previous price level, or you may use another variable to get the Average Entry Price. Your syntax for using BarsSinceEntryExecution() looks valid, however, I may suggest to take a look at Position.AveragePrice. I have provided a link to documentation and a reference sample we have available that describes how a breakeven can be coded in NinjaScript. You may substitute SetStopLoss() and simplify it if you wish.

        As for historical calculations that we see when we enable our strategies and in the Strategy Analyzer, standard fill resolution will create "virtual bars" to mimic the price flow, while high order fill resolution will substitute additional data for intra-bar fills. There are also fundamental differences between historical and realtime data. I will provide links to our Strategy Analyzer documentation for further reading.

        Publicly available documentation and sample code can be found below.

        Position.AveragePrice - https://ninjatrader.com/support/help...erageprice.htm

        SampleOnOrderUpdate - https://ninjatrader.com/support/foru...ead.php?t=7499

        Understanding Historical Fill Processing - https://ninjatrader.com/support/help...ical_fill_.htm

        Discrepancies between realtime and backtest - https://ninjatrader.com/support/help...ime_vs_bac.htm

        Please let us know if we can be of further assistance.
        Attached Files
        JimNinjaTrader Customer Service

        Comment

        Latest Posts

        Collapse

        Topics Statistics Last Post
        Started by Mestor, 03-10-2023, 01:50 AM
        16 responses
        388 views
        0 likes
        Last Post z.franck  
        Started by rtwave, 04-12-2024, 09:30 AM
        4 responses
        31 views
        0 likes
        Last Post rtwave
        by rtwave
         
        Started by yertle, Yesterday, 08:38 AM
        7 responses
        29 views
        0 likes
        Last Post yertle
        by yertle
         
        Started by bmartz, 03-12-2024, 06:12 AM
        2 responses
        22 views
        0 likes
        Last Post bmartz
        by bmartz
         
        Started by funk10101, Today, 12:02 AM
        0 responses
        7 views
        0 likes
        Last Post funk10101  
        Working...
        X